C# 中靜態建構函式和例項建構函式的區別
靜態建構函式
靜態建構函式是使用 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(); } } }
輸出
This is Static Constructor This is Instance Constructor This is Instance Constructor First Value = 70 Second Value = 110 First Value = 70 Second Value = 200
廣告