평소에 생각없이(?) 코딩하다가 최근에 WPF 스터디를 진행하면서 CustomControl를 만들때
아래의 코드로 항상 시작하는 것을 보게 되었는데요.
public class MyCustomControl : Control
{
static MyCustomControl()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(MyCustomControl), new FrameworkPropertyMetadata(typeof(MyCustomControl)));
}
// Add your custom properties, events, and methods here
}
static MyCustomControl() 생성자는 언제 실행이 될까 하는 거였습니다.
chatGPT에도 물어보고 했지만, 결국 답은 MSDN에 있었네요.
A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed only once. It is called automatically before the first instance is created or any static members are referenced. A static constructor will be called at most once.
정적 생성자는 정적 데이터를 초기화하거나 한 번만 수행해야 하는 특정 작업을 수행하는 데 사용됩니다. 첫 번째 인스턴스가 생성되거나 정적 멤버가 참조되기 전에 자동으로 호출됩니다. 정적 생성자는 최대 한 번만 호출됩니다.
Static constructor is called at most one time, before any instance constructor is invoked or member is accessed.
정적 생성자는 인스턴스 생성자가 호출되거나 멤버에 액세스하기 전에 최대 한 번만 호출됩니다.
The sample output verifies that the static constructor runs only one time, even though two instances of Bus are created, and that it runs before the instance constructor runs.
샘플 출력에서는 Bus의 인스턴스가 두 개 생성되더라도 정적 생성자가 한 번만 실행되고 인스턴스 생성자가 실행되기 전에 정적 생성자가 실행되는 것을 확인할 수 있습니다.
정적 생성자는 직접 호출할 수 없으며 공용 언어 런타임(CLR)에서만 호출할 수 있습니다. 자동으로 호출됩니다.
사용자는 프로그램에서 정적 생성자가 언제 실행되는지 제어할 수 없습니다.
정적 생성자는 자동으로 호출됩니다. 첫 번째 인스턴스가 생성되거나 해당 클래스에서 선언된 정적 멤버(기본 클래스가 아님)가 참조되기 전에 클래스를 초기화합니다. 정적 생성자는 인스턴스 생성자보다 먼저 실행됩니다. 정적 필드 변수 이니셜라이저가 정적 생성자의 클래스에 있는 경우 클래스 선언에 표시된 텍스트 순서대로 실행됩니다. 이니셜라이저는 정적 생성자가 실행되기 직전에 실행됩니다.
정적 필드를 초기화할 정적 생성자를 제공하지 않으면 모든 정적 필드는 C# 유형의 기본값에 나열된 대로 기본값으로 초기화됩니다.