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).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…