I have a big static array of delegates that is the same for all instances of the class. I want to put references to instance methods in the array, i.e. open instance delegates. The compiler gives me an error. How do I do that?
Example code:
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
}
Some ideas that I’ve considered: providing all instance fields as parameters, but this becomes unwieldy very quickly. Initializing the list of handlers for each instance, but this would hurt performance very much (I need many instances of this class).
Based on Jon Skeet’s answer on another question, the following will work:
Direct support in C# would be much nicer. Maybe there is another way to do this that does not involve the indirection and extra typing?