C# 中的静态构造函数是什么?
csharpprogrammingserver side programming更新于 2025/10/13 20:52:17
静态构造函数是使用 static 修饰符声明的构造函数。它是类中执行的第一个代码块。因此,静态构造函数在类的生命周期中只执行一次。
以下是 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();
}
}
}

