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
}

我考虑过的一些想法:将所有实例字段作为参数提供,但这很快就会变得笨拙。为每个实例初始化处理程序列表,但这会极大地损害性能(我需要这个类的许多实例)。

4

1 回答 1

0

根据Jon Skeet对另一个问题的回答,以下方法将起作用:

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# 中的直接支持会更好。也许还有另一种不涉及间接和额外输入的方法?

于 2013-02-05T14:13:22.877 回答