2013-02-05 4 views
0

클래스의 모든 인스턴스에 대해 동일한 대리자 정적 배열이 있습니다. 배열에 인스턴스 메서드에 대한 참조를 넣으려고합니다. 즉, 열린 인스턴스 대리자입니다. 컴파일러에서 오류가 발생했습니다. 어떻게해야합니까?정적 대리자 배열의 인스턴스 메서드


예제 코드 :이 매우 빠르게 다루기가된다 매개 변수로 모든 인스턴스 필드를 제공하지만, :

public class Interpreter 
{ 
    // >7 instance fields that almost all methods need. 

    private static readonly Handler[] Handlers = new Handler[] 
    { 
     HandleNop,   // Error: No overload for `HandleNop` matches delegate 'Handler' 
     HandleBreak, 
     HandleLdArg0, 
     // ... 252 more 
    }; 

    private delegate void Handler(Interpreter @this, object instruction); 

    protected virtual void HandleNop(object instruction) 
    { 
     // Handle the instruction and produce a result. 
     // Uses the 7 instance fields. 
    } 

    protected virtual void HandleBreak(object instruction) {} 
    protected virtual void HandleLdArg0(object instruction) {} 
    // ... 252 more 
} 

내가 생각 한 몇 가지 아이디어. 각 인스턴스에 대한 핸들러 목록을 초기화하지만 성능이 많이 손상됩니다 (이 클래스의 인스턴스가 많이 필요합니다).

답변

0

또 다른 질문에 Jon Skeet's answer을 바탕으로, 다음 작동합니다 : C#에서

public class Interpreter 
{ 
    private static readonly Handler[] Handlers = new Handler[] 
    { 
     (@this, i) => @this.HandleNop(i), 
     (@this, i) => @this.HandleBreak(i), 
     (@this, i) => @this.HandleLdArg0(i), 
     // ... 252 more 
    }; 

    private delegate void Handler(Interpreter @this, object instruction); 

    protected virtual void HandleNop(object instruction) {} 
    protected virtual void HandleBreak(object instruction) {} 
    protected virtual void HandleLdArg0(object instruction) {} 
} 

직접 지원이 훨씬 좋네요 될 것이다. 간접 지정과 추가 타이핑을 포함하지 않는 다른 방법이있을 수 있습니까?

관련 문제