我有一个静态类,我想要构建一个SQLConnectionString。
public static class SharedUtilities
{
public static SqlConnectionStringBuilder connectionString = new SqlConnectionStringBuilder();
SharedUtilities()
{
connectionString.DataSource = "dx2v";
connectionString.InitialCatalog = "Q619410";
connectionString.UserID = "tunnelld";
connectionString.Password = "david";
}
}
这不起作用,因为你可以在静态类上有构造函数。那我该怎么做?
答案 0 :(得分:4)
您忘记了构造函数中的static
关键字:
static SharedUtilities()
因为你省略了它,它默认为private
,这对静态类无效。
答案 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