I’d like to create a static array that contains delegates. I will use this array to look up the delegate that I need. For example:
class HandlerID
{
public int ID { get; set; }
public Func<int, bool> Handler { get; set; }
}
protected const HandlerID[] HandlerIDs = {
new SectionRenderer() { ID = SectionTypes.Type1, Handler = MyType1Handler },
new SectionRenderer() { ID = SectionTypes.Type2, Handler = MyType2Handler },
// Etc.
}
protected bool MyType1Handler(int arg)
{
return false;
}
// Etc.
However, the assignments to Handler in the HandlerID array gives the following error:
An object reference is required for the non-static field, method, or property ‘MyType1Handler(int)’
I’d prefer the array is const so it doesn’t have to be initialized for every instance of my class. Is there any way to store an instance method in a static array?
That doesn’t make sense.
When you call the delegates in the array, they need an instance of your class to operate on.
Therefore, you need a separate set of delegates for each class instance.
If the methods don’t actually need an instance to operate on, you can make them
static, which will fix the problem.Alternatively, you can take the instance as a parameter to the delegate, and use a lambda expression that calls the method:
Handler = (instance, arg) => instance.MyType1Handler(arg)