C#Static静态构造函数用于初始化静态字段。它还可以用于执行任何仅执行一次的操作。在创建第一个实例或引用任何静态成员之前自动调用。
静态构造函数需要记住的几点
- C# 静态构造函数不能有任何修改器或参数。
- C# 隐式调用静态构造函数。它无法明确调用。
C#静态构造函数示例
让无涯教程看看静态构造函数的示例,它初始化Account类中的Static静态字段rateOfInterest。
using System;
public class Account
{
public int id;
public String name;
public static float rateOfInterest;
public Account(int id, String name)
{
this.id = id;
this.name = name;
}
static Account()
{
rateOfInterest = 9.5f;
}
public void display()
{
Console.WriteLine(id + " " + name+" "+rateOfInterest);
}
}
class TestEmployee{
public static void Main(string[] args)
{
Account a1 = new Account(101, "Sonoo");
Account a2 = new Account(102, "Mahesh");
a1.display();
a2.display();
</span><span class="pun">}</span><span class="pln">
</span><span class="pun">}</span></pre></div>
输出:
101 Sonoo 9.5
102 Mahesh 9.5
参考链接