C#Static静态构造函数用于初始化静态字段。它还可以用于执行任何仅执行一次的操作。在创建第一个实例或引用任何静态成员之前自动调用。
让无涯教程看看静态构造函数的示例,它初始化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(); } }
输出:
101 Sonoo 9.5 102 Mahesh 9.5
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)