开发者

Store Static Reference to Instance Method?

I'd like to create a static array that contains delegates. I will use this array to look开发者_如何学Python 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)


You cannot declare a const array in C#, try readonly which ensures the pointer to the array (the instance) will not change but as far as I know there is no way to declaratively prevent the elements from being changed.


You can't create a delegate to a static function and you can't create a delegate to a function in an non existent object instance. However you can store the MethodInfo and at a later time invoke that on an instance.

 // Use MethodInfo instead of Func in HandlerId
 public MethodInfo Method { get; set; }

 // Create the static list of handlers
 protected static HandlerID[] HandlerIDs = {    
  new SectionRenderer() { ID = SectionTypes.Type1, Method = typeof(MyHandlersClass).GetMethod("MyType1Handler") },    
  new SectionRenderer() { ID = SectionTypes.Type2, Method = typeof(MyHandlersClass).GetMethod("MyType2Handler") },    
   // Etc.
  }

  // invoke at some point
  HandlersIds[0].Method.Invoke(aninstanceobject, new object[] { arg } );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜