我有几个关于C#中静态构造函数的问题.
**已编辑
public class Test
{
// Static constructor:
static Test()
{
Console.WriteLine("Static constructor invoked.");
}
public static void TestMethod()
{
Console.WriteLine("TestMethod invoked.");
}
}
class Sample
{
static void Main()
{
Test.TestMethod();
}
}
Run Code Online (Sandbox Code Playgroud)
输出:调用静态构造函数.调用了TestMethod.所以,这意味着静态构造函数将被调用一次.如果我们再次调用Test.TestMethod(); 静态构造函数不会调用.
任何指针或建议将不胜感激'
谢谢
静态构造函数是在加载类时仅在ONCE上执行的构造函数.每次创建对象时都会执行常规(非静态)构造函数.
看看这个例子:
public class A
{
public static int aStaticVal;
public int aVal;
static A() {
aStaticVal = 50;
}
public A() {
aVal = aStaticVal++;
}
}
Run Code Online (Sandbox Code Playgroud)
并考虑以下代码:
A a1 = new A();
A a2 = new A();
A a3 = new A();
Run Code Online (Sandbox Code Playgroud)
在这里,static构造函数将被称为第一次也是唯一一次程序的执行过程中.而常规构造函数将被调用三次(每次对象实例化一次).
static构造函数通常用于初始化静态字段,例如,为静态字段分配初始值.请记住,您只能访问构造函数static上的成员(方法,属性和字段)static.
如果需要"多次执行静态构造函数",则不能这样做.相反,您可以在静态方法中"多次"运行要运行的代码,并在需要时调用它.就像是:
public class A {
public static int a, b;
static A() {
A.ResetStaticVariables();
}
public static void ResetStaticVariables() {
a = b = 0;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
595 次 |
| 最近记录: |