2013-02-05 40 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另一個問題,下面的工作:

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) {} 
} 

在C#中直接支持將會更加美好。也許有另外一種方法可以做到這一點,不涉及間接和額外的輸入?