다음 코드 :왜 static 필드 초기화가 정적 생성자보다 먼저 발생합니까?
static void Main(string[] args)
{
Console.WriteLine("0");
string h = Foo.X;
Console.WriteLine("2");
}
public static class Foo
{
public static string X = ((Func<string, string>)delegate(string g)
{
Console.WriteLine(g);
return (g);
})("_aaa");
static Foo()
{
Console.WriteLine("ctor");
}
}
가 인쇄됩니다 : 나는 (정적 생성자 등이 부착 된 /)를 beforefieldinit
행동에 대해 알고
0
_aaa
ctor
2
. (출력 단위) ctor
이_aaa
후 왜 내가 이해가 안
것은 무엇입니까?
아무런 의미가 없습니다. 생성자에서 변수를 초기화하려면 어떻게해야합니까?
질문
X
의 초기화가 ctor
앞에있는 이유는 무엇?
비 정적 필드와 비 정적 생성자에 대해서도 비슷합니다.'class Foo {public string X = "A"; public Foo() {X = "B"; }}'이렇게하면 ('new Foo()) .X'를하면''B ''의 할당이 마지막으로 발생했기 때문에''A''가 아니라''B "'를 얻습니다. 값). –
@JeppeStigNielsen 설명해 주셔서 감사합니다 –