C# 中的靜態建構函式是什麼?


靜態建構函式是使用靜態修飾符宣告的建構函式。它是類中執行的第一段程式碼。因此,靜態建構函式在類的生命週期中僅執行一次。

以下是 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();
      }
   }
}

更新於: 2020 年 6 月 21 日

371 瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.