C# 静态委托数组中的实例方法
我有一个很大的静态委托数组,对于类的所有实例都是相同的。我想在数组中放置对实例方法的引用,即打开实例委托。编译器给了我一个错误。我该怎么做C# 静态委托数组中的实例方法,c#,delegates,C#,Delegates,我有一个很大的静态委托数组,对于类的所有实例都是相同的。我想在数组中放置对实例方法的引用,即打开实例委托。编译器给了我一个错误。我该怎么做 示例代码: public class Interpreter { // >7 instance fields that almost all methods need. private static readonly Handler[] Handlers = new Handler[] { HandleNop
示例代码:
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
}
我考虑过的一些想法:提供所有实例字段作为参数,但这很快就会变得很难处理。初始化每个实例的处理程序列表,但这会严重影响性能(我需要这个类的许多实例)。基于另一个问题,以下操作将起作用:
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#中提供直接支持会更好。也许有另一种方法可以做到这一点,不涉及间接和额外的键入