针对委托检查 MethodInfo

Checking a MethodInfo against a delegate(针对委托检查 MethodInfo)
本文介绍了针对委托检查 MethodInfo的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何确定 MethodInfo 是否适合不同的委托类型?

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

bool IsMyDelegate(MethodInfo method);

我得到了一个 MethodInfo 对象,想知道它是否适合委托接口.除了明显的

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;
    }

推荐答案

如果method是静态方法:

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

如果 method 是实例方法:

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

(不幸的是,在这种情况下您需要一个实例,因为 Delegate.CreateDelegate 将尝试绑定一个委托实例,尽管在这种情况下,我们关心的是委托 是否可以 被创建还是不是.)

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

在这两种情况下,诀窍基本上是要求 .NET 从 MethodInfo 创建所需类型的委托,但如果方法的签名错误,则返回 null 而不是抛出异常.然后针对 null 的测试告诉我们委托是否具有正确的签名.

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

这篇关于针对委托检查 MethodInfo的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)