Build a static delegate from non-static method

后端 未结 5 1192
无人共我
无人共我 2021-01-06 08:28

I need to create a delegate to a non-static method of a class. The complications is that at the time of creation I don\'t have an intance to the class, only its class defini

5条回答
  •  滥情空心
    2021-01-06 08:57

    You can use Delegate.CreateDelegate to dynamically construct a delegate for a particular target instance given a MethodInfo. You can look up the MethodInfo with Type.GetMethod (Reflection) and cache it for later use creating the delegate.

    For example, this would grab the "GetHashCode" method and bind it to the 'this' instance:

            var method = typeof(Object).GetMethod("GetHashCode");
            var del = (Func)Delegate.CreateDelegate(typeof(Func), this, method);
    

    There are more subtleties if you have more than one overload of the method, but there are additional GetMethod parameters you can use to disambiguate, if necessary.

提交回复
热议问题