Basic/C#

[C#] CS0120: non-static field 에러

에반황 2019. 3. 19. 11:43

Error 메시지

error CS0120: An object reference is required for the non-static field, method, or property

 

발생 상황

class Program
{
    void TestMethod() 
    {    
        // Process
    }

    static void Main(string[] args)
    {
        TestMethod();
    }
}

TestMethod()를 진행하려고 하는데, 위와 같은 에러 메시지가 떴다.

 

해결 방법1

class Program
{
    static void TestMethod() 
    {    
        // Process
    }

    static void Main(string[] args)
    {
        TestMethod();
    }
}

말 그대로 non-static field인 메서드를 실행하려고 했기 때문에 났던 에러이다. static을 사용하면 인스턴스를 생성하지 않아도 사용할 수 있는 정적메서드가 된다. 메서드에 static을 붙여주면 해결 완료.

 

해결 방법2

class Program
{
    void TestMethod() 
    {    
        // Process
    }

    static void Main(string[] args)
    {
        Program p = new Program();
        p.TestMethod();
    }
}

static한 메서드로 사용하고 싶지 않다면, 해당 객체를 생성한 후 접근하면 해결 완료.

 

 



반응형