[c#] 정적 멤버가 정적이지 않은 멤버에 접근할 수 없는 이유
정적 메떠드와 프라퍼티는 static 선언이 되지 않은 필드와 이벤트에 접근할 수 없다. 정적 멤버는 프로그램이 실행될 때 로드되는데 이때 정적이지 않은 멤버는 로드되지 않은 상태이기 때문이다.
If your class contains static fields, provide a static constructor that initializes them when the class is loaded.
– Static Classes and Static Class Members (C# Programming Guide)
class Program
{
static void Main(string[] args)
{
TestMethod1(); // error
TestMethod2(); // works well
}
public void TestMethod1()
{
// ...
}
public static void TestMethod2()
{
// ...
}
}
참고로 여기에서 static의 반대를 dynamic이라 하지 않고 non-static이라 하는 데에 유의한다. 여기에서 static이란 엄밀하게는 정적 즉 멈춰 있다는 뜻이 아니라 단순하게 인스턴스를 만들 필요가 없는 것이라는 의미이기 때문이다.