C# 静态/单例/类似的东西?
我在OOP/设计模式方面没有太多经验,下面是我的问题 我希望在解决方案中的所有Visual Studio项目中使用字符串变量的值。 也就是说,我在我的一个C#项目中创建了一个名为strVar的变量。所有其他项目都参考了它 实际上,我想要的是——字符串变量的值必须在加载Dll(或第一次访问Class.variable)后计算,而不是每次访问该变量时计算 [当第一次访问该类时-我希望计算该值并在Dll/App域的整个生命周期内保持该值。] 即,字符串值在应用程序的每次安装中都会不同,并且不能使用.config文件 有什么方法可以做到这一点吗???考虑使用 例如C# 静态/单例/类似的东西?,c#,sharepoint-2010,C#,Sharepoint 2010,我在OOP/设计模式方面没有太多经验,下面是我的问题 我希望在解决方案中的所有Visual Studio项目中使用字符串变量的值。 也就是说,我在我的一个C#项目中创建了一个名为strVar的变量。所有其他项目都参考了它 实际上,我想要的是——字符串变量的值必须在加载Dll(或第一次访问Class.variable)后计算,而不是每次访问该变量时计算 [当第一次访问该类时-我希望计算该值并在Dll/App域的整个生命周期内保持该值。] 即,字符串值在应用程序的每次安装中都会不同,并且不能使用.c
public class ImportantData
{
public static string A_BIG_STRING;
// This is your "static constructor"
static ImportantData()
{
A_BIG_STRING = CalculateBigString();
}
private static string CalculateBigString()
{
return ...;
}
}
正如文档所述,除其他外,静态构造函数拥有以下属性:
将自动调用静态构造函数来初始化该类
在创建第一个实例或创建任何静态成员之前
参考
静态构造函数就是答案。一次性初始化(当您第一次访问类时),这正是您需要的。在静态构造函数中进行初始化。每次运行应用程序的特定安装时,是否需要相同的字符串?
public SomePubliclyVisibleClass
{
private static _strVal = ComputedStrVal();//we could have a public field, but
//since there are some things that
//we can do with a property that we
//can't with a field and it's a breaking
//change to change from one to the other
//we'll have a private field and
//expose it through a public property
public static StrVal
{
get { return _strVal; }
}
private static string ComputedStrVal()
{
//code to calculate and return the value
//goes here
}
}