静态构造函数的意义
废话不说,上Dome!
/// <summary>
/// 静态构造函数,模拟类
/// </summary>
public class MyStaticClass
{
public static readonly string myStaticString;
public string myString;
/// <summary>
/// 静态构造函数
/// </summary>
static MyStaticClass()
{
myStaticString = "静态构造函数初始化";
}
/// <summary>
/// 实例构造函数
/// </summary>
public MyStaticClass()
{
myString = "默认实例构造函数";
}
/// <summary>
/// 实例构造函数
/// </summary>
/// <param name="param">传入参数</param>
public MyStaticClass(string param)
{
myString = param;
}
}
-------------------------------------------------------------------
/// <summary>
/// 调用静态构造函数
/// </summary>
private void BindInfo()
{
string strValue = string.Empty;
MyStaticClass myObj_1 = new MyStaticClass();
strValue = myObj_1.myString;
MyStaticClass myObj_2 = new MyStaticClass("赋值的实例构造函数");
strValue=myObj_2.myString;
string strStatic= MyStaticClass.myStaticString;
}
总结:
- 一个类中只能有一个静态构造函数
- 静态构造函数不能有参数,返回值,访问标识符。
- 静态函数只在加载类的时候执行一次,而实例构造函数,在类实例化时,都会执行。
- 一个类中,静态构造函数和无参构造函数,可以同时存在。因为加载类是调用静态构造函数;实例化类时,调用实例构造函数。
- 静态构造函数的调用要早于实例构造函数。
- 静态构造函数,仅执行一次。s
浙公网安备 33010602011771号