将数据分配给静态类中的对象

时间:2015-05-27 18:49:13

标签: c#

我有一个静态类,我想要构建一个SQLConnectionString。

public static class SharedUtilities
{
    public static SqlConnectionStringBuilder connectionString = new SqlConnectionStringBuilder();

    SharedUtilities()
    {
        connectionString.DataSource = "dx2v";
        connectionString.InitialCatalog = "Q619410";
        connectionString.UserID = "tunnelld";
        connectionString.Password = "david";
    }
}

这不起作用,因为你可以在静态类上有构造函数。那我该怎么做?

2 个答案:

答案 0 :(得分:4)

您忘记了构造函数中的static关键字:

static SharedUtilities()

因为你省略了它,它默认为private,这对静态类无效。

请参阅Static Constructors (MSDN)

答案 1 :(得分:1)

一种方法是使用一个按需构建对象的属性(创建并填写私有后备属性)。

public static class SharedUtilities
{
    private static SqlConnectionStringBuilder connectionString = null;

    public static SqlConnectionStringBuilder ConnectionString
    {
        get
        {
            if (connectionString == null)
            {
                connectionString = new SqlConnectionStringBuilder()
                {
                    DataSource = "dx2v",
                    InitialCatalog = "Q619410",
                    UserID = "tunnelld",
                    Password = "david",
                };
             }
             return connectionString;
         }
    }
}

供参考:Lazy Loading