C#

2017-09-19 8 views
-1

에서 정적이 아닌 메서드를 사용하여 대리자를 사용하여 클로저를 가져 오기 위해 Using delegates with non static methods [no picked answer] 과 같은 질문을합니다.C#

그래서 나는 @ 아담 마샬의 솔루션을 사용, 작동,하지만 최대한 빨리 시작으로, 즉, Testit() 그것을 사용 :

A object reference is required for the non-static field, method, or property

:

using System; 

public class TestClass 
{ 
    private delegate void TestDelegate(); 
    TestDelegate testDelegate; 

    public TestClass() 
    { 
     testDelegate = new TestDelegate(MyMethod); 
    } 

    public static void Testit() 
    { 
     testDelegate(); 
    } 

    private virtual void MyMethod() 
    { 
     Console.WriteLine("Foobar"); 
    } 
} 

public class Program 
{ 
    public static void Main() 
    { 
     Console.WriteLine("Hello World"); 
     TestClass.Testit(); 
    } 
} 

그것은 followig 오류를 제공하기 시작 당신은 test it out here 일 수 있습니다. 어떻게 고칠 수 있습니까? (가능한 경우 다른 게시물로 이동하지 말고 읽었지만 이해할 수는 없습니다.) Thx.

+2

난 당신이 코드와 해당 오류를 얻을 것 방법을 모르겠어요. 이것은 허용되지 않는 정적 멤버 내에서 비 ​​정적 멤버를 사용하려고합니다. 인스턴스 구성원을 호출하려면 인스턴스가 필요합니다. 바이올린은 인스턴스가 필요하다는 오류를 생성합니다. –

답변

1

모든 것이 정적이거나 모든 것이 인스턴스 여야합니다. 믹싱과 매칭 때문에 문제가 생길 수 있습니다. 정적

모든 : 복제 된

using System; 

public class TestClass 
{ 
    private delegate void TestDelegate(); 
    static TestDelegate testDelegate; //<-- static 

    static TestClass()     //<-- static 
    { 
     testDelegate = new TestDelegate(MyMethod); 
    } 

    public static void Testit() 
    { 
     testDelegate(); 
    } 

    private static void MyMethod() 
    { 
     Console.WriteLine("Foobar"); 
    } 
} 

public class Program 
{ 
    public static void Main() 
    { 
     Console.WriteLine("Hello World"); 
     TestClass.Testit(); 
    } 
} 

모든 : (두 예에서 모두 동일)

using System; 

public class TestClass 
{ 
    private delegate void TestDelegate(); 
    TestDelegate testDelegate; 

    public TestClass() 
    { 
     testDelegate = new TestDelegate(MyMethod); 
    } 

    public void Testit() 
    { 
     testDelegate(); 
    } 

    private void MyMethod() 
    { 
     Console.WriteLine("Foobar"); 
    } 
} 

public class Program 
{ 
    public static void Main() 
    { 
     Console.WriteLine("Hello World"); 
     var t = new TestClass(); 
     t.Testit(); //<-- non-static 
    } 
} 

출력 :

Hello World 
Foobar 
0

당신은 액션 C#을 내부 대리자를 사용할 수 있습니다. 위임자를 지정하지 않아도됩니다. 그런 다음 정적 방법으로 개체를 새로 만들 수 있습니다.

using System; 

public class TestClass 
{ 

    Action testDelegate; 

    public TestClass() 
    { 
     testDelegate = new Action(MyMethod); 
    } 

    public static void Testit() 
    { 
     TestClass ts = new TestClass(); 
     ts.testDelegate(); 
    } 

    private void MyMethod() 
    { 
     Console.WriteLine("Foobar"); 
    } 
} 

public class Program 
{ 
    public static void Main() 
    { 
     Console.WriteLine("Hello World"); 
     TestClass.Testit(); 
    } 
} 

출력 :

Hello World 
Foobar 
+0

답장을 보내 주셔서 감사합니다. @StuartSmith, 내가 이해할 수있는 하나이기 때문에 다른 것을 고른 것입니다 (나는'행동'을 모른다). – xpt