번역/C# Notes for Professionals
42.2: 정적 (Static) 클래스의 수명 (lifetime)
노초코
2022. 5. 19. 23:31
Section 42.2: 정적 (Static) 클래스의 수명 (lifetime)
정적 (static) 클래스는 실제 멤버 접근시점에 지연된 (lazy) 초기화를 수행하며, 어플리케이션 도메인이 유지되는 동안 수명을 같이한다.
void Main() {
Console.WriteLine("Static classes are lazily initialized");
Console.WriteLine("The static constructor is only invoked when the class is first accessed");
Foo.SayHi();
Console.WriteLine("Reflecting on a type won't trigger its static .ctor");
var barType = typeof (Bar);
Console.WriteLine("However, you can manually trigger it with System.Runtime.CompilerServices.RuntimeHelpers ");
RuntimeHelpers.RunClassConstructor(barType.TypeHandle);
}
// 다른 메소드 및 클래스들을 여기에 선언한다
public static class Foo {
static Foo() {
Console.WriteLine("static Foo.ctor");
}
public static void SayHi() {
Console.WriteLine("Foo: Hi");
}
}
public static class Bar {
static Bar() {
Console.WriteLine("static Bar.ctor");
}
}
실행 결과:
Static classes are lazily initialized
The static constructor is only invoked when the class is first accessed
static Foo.ctor
Foo: Hi
Reflecting on a type won't trigger its static .ctor
However, you can manually trigger it with System.Runtime.CompilerServices.RuntimeHelpers
static Bar.ctor
본 문서는 C# Notes for Professionals (라이센스:CC-BY-SA) 를 한글로 번역한 문서입니다. 번역상 오류가 있을 수 있으므로 정확한 내용은 원본 문서를 참고하세요.
[출처] https://books.goalkicker.com/CSharpBook/
반응형