静态委托数组中的实例方法

时间:2013-02-05 14:13:23

标签: c# delegates

我有一个很大的静态委托数组,对于所有类的实例都是一样的。我想在数组中引用实例方法,即 open instance delegates 。编译器给我一个错误。我该怎么做?


示例代码:

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
}

我考虑过的一些想法:提供所有实例字段作为参数,但这很快变得难以处理。初始化每个实例的处理程序列表,但这会严重影响性能(我需要这个类的很多实例)。

1 个答案:

答案 0 :(得分: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#中的直接支持会更好。也许有另一种方法可以做到这一点,不涉及间接和额外的打字?