C# 静态构造函数用于初始化静态字段。它还可用于执行任何只执行一次的操作。在创建第一个实例或引用任何静态成员之前自动调用它。
C# 静态构造函数不能有任何修饰符或参数。
C# 静态构造函数被隐式调用。它不能被显式调用。
让我们看看静态构造函数的例子,它在 Account 类中初始化静态字段 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(); } }
输出:
101 Sonoo 9.5 102 Mahesh 9.5