C# delegate not bound to an instance?

后端 未结 4 1967
盖世英雄少女心
盖世英雄少女心 2021-01-04 08:47

Is there a way to store a delegate without binding it to an object like how you can with a MethodInfo? Right now I am storing a MethodInfo so I can give it the object to cal

4条回答
  •  离开以前
    2021-01-04 09:30

    You can use the Delegate.CreateDelegate method to create a strongly-typed delegate for a MethodInfo.

    If you don't know the method's signature at compile-time, you can either create a Func<...> using Reflection, or create a lambda expression that invokes the MethodInfo:

    MethodInfo methodInfo = ...;
    object thisObj = ...;
    Func callMethod = args => methodInfo.Invoke(thisObj, args);
    

    (This is called currying)

    Note that this will still have the performance hit from reflection every time the delegate is called, unlike Delegate.CreateDelegate.

提交回复
热议问题