내용 보기
작성자
관리자 (IP : 172.17.0.1)
날짜
2021-01-05 09:15
제목
[C#] .NET 런타임에 따라 달라지는 정적 필드의 초기화 유무
using System;
namespace ConsoleApp1
{
static class Program
{
static MyStatic _instance = new MyStatic();
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
internal class MyStatic
{
static MyStaticLevel2 _instance = new MyStaticLevel2();
public MyStatic()
{
Console.WriteLine("MyStatic.ctor");
}
}
internal class MyStaticLevel2
{
public MyStaticLevel2()
{
Console.WriteLine("MyStaticLevel2.ctor");
}
}
[닷넷 프레임워크] MyStaticLevel2.ctor MyStatic.ctor Hello World! [닷넷 코어] Hello World!
Why isn't this C# instance constructor being called, unless there is a reference to a non-static member? [duplicate] ; https://stackoverflow.com/questions/52278729/why-isnt-this-c-sharp-instance-constructor-being-called-unless-there-is-a-refe
using System;
namespace ConsoleApp1
{
static class Program
{
static MyStatic _instance = new MyStatic();
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
// 사용자가 정의한 정적 생성자에는 C# 컴파일러가 beforefieldinit 속성을 부여하지 않음
static Program()
{
// C# 컴파일러는 정적 필드에 대한 사용자 코드를 이곳으로 병합해서 빌드
}
}
}
internal class MyStatic
{
static MyStaticLevel2 _instance = new MyStaticLevel2();
public MyStatic()
{
Console.WriteLine("MyStatic.ctor");
}
static MyStatic()
{
}
}
internal class MyStaticLevel2
{
public MyStaticLevel2()
{
Console.WriteLine("MyStaticLevel2.ctor");
}
}
namespace ConsoleApp1
{
static class Program
{
static MyStatic _instance;
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
static Program()
{
// 명시적으로 사용자 초기화 코드를 정적 생성자로 이동
_instance = new MyStatic();
}
}
}
internal class MyStatic
{
static MyStaticLevel2 _instance;
public MyStatic()
{
Console.WriteLine("MyStatic.ctor");
}
static MyStatic()
{
_instance = new MyStaticLevel2();
}
}
|
출처1
https://www.sysnet.pe.kr/Default.aspx?mode=2&sub=0&pageno=0&detail=1&wid=12473
출처2