정적 생성자
정적 생성자는 정적 한정자를 사용하여 선언된 생성자입니다. 클래스에서 실행되는 첫 번째 코드 블록입니다. 이를 통해 정적 생성자는 클래스의 수명 주기에서 한 번만 실행됩니다.
인스턴스 생성자
인스턴스 생성자는 인스턴스 데이터를 초기화합니다. 인스턴스 생성자는 클래스의 객체가 생성될 때 호출됩니다.
다음 예는 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