Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
406 views
in Technique[技术] by (71.8m points)

c# - Checking a MethodInfo against a delegate

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...