问题描述
如何确定 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)