Checking a MethodInfo against a delegate

蹲街弑〆低调 提交于 2019-11-28 09:22:12

If method is a static method:

bool isMyDelegate =
  (Delegate.CreateDelegate(typeof(MyDelegate), method, false) != null);

If method is an instance method:

bool isMyDelegate =
  (Delegate.CreateDelegate(typeof(MyDelegate), someObj, method, false) != null)

(Unfortunately you need an instance in this case because Delegate.CreateDelegate is going to try to bind a delegate instance, even though in this case all we care about it whether the delegate could be created or not.)

In both cases, the trick is basically to ask .NET to create a delegate of the desired type from the MethodInfo, but to return null rather than throwing an exception if the method has the wrong signature. Then testing against null tells us whether the delegate had the right signature or not.

Note that because this actually tries to create the delegate it will also handle all the delegate variance rules for you (e.g. when the method return type is compatible but not exactly the same as the delegate return type).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!