静态构造函数是使用静态修饰符声明的构造函数。它是在类中执行的第一段代码。这样,静态构造函数在类的生命周期中仅执行一次。
实例构造函数初始化实例数据。创建类的对象时,将调用实例构造函数。
以下示例显示了C#中的静态构造函数和实例构造函数之间的区别。
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Difference { class Demo { static int val1; int val2; static Demo() { Console.WriteLine("This is Static Constructor"); val1 = 70; } public Demo(int val3) { Console.WriteLine("This is Instance Constructor"); val2 = val3; } private void show() { Console.WriteLine("First Value = " + val1); Console.WriteLine("Second Value = " + val2); } static void Main(string[] args) { Demo d1 = new Demo(110); Demo d2 = new Demo(200); d1.show(); d2.show(); Console.ReadKey(); } } }
输出结果
This is Static Constructor This is Instance Constructor This is Instance Constructor First Value = 70 Second Value = 110 First Value = 70 Second Value = 200