Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How can I determine if a MethodInfo fits a distinct Delegate Type?

bool IsMyDelegate(MethodInfo method);

Edit: I'm given a MethodInfo object and want to know if it fits the delegate interface. Apart from the obvious

    private bool IsValidationDelegate(MethodInfo method)
    {
        var result = false;
        var parameters = method.GetParameters();
        if (parameters.Length == 2 &&
            parameters[0].ParameterType == typeof(MyObject1) &&
            parameters[1].ParameterType == typeof(MyObject2) &&
            method.ReturnType == typeof(bool))
        {
            result = true;
        }
        else
        {
            m_Log.Error("Validator:IsValidationDelegate", "Method [...] is not a ValidationDelegate.");
        }
        return result;
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
383 views
Welcome To Ask or Share your Answers For Others

1 Answer

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...