views:

81

answers:

1

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;
    }
+5  A: 

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

itowlson
nice. thanks, exactly what I needed.
Sven Hecht