Computer >> Máy Tính >  >> Lập trình >> C#

Hàm tạo tĩnh trong C # là gì?

Một phương thức khởi tạo tĩnh là một phương thức khởi tạo được khai báo bằng cách sử dụng một công cụ sửa đổi tĩnh. Nó là khối mã đầu tiên được thực thi trong một lớp. Cùng với đó, một hàm tạo tĩnh chỉ thực thi một lần trong vòng đời của lớp.

Sau đây là một ví dụ về các hàm tạo tĩnh trong C # -

Ví dụ

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