检查针对委托的MethodInfo
如何确定MethodInfo是否适合不同的委托类型?
bool IsMyDelegate(MethodInfo method);
编辑:我给了一个MethodInfo对象,想知道它是否适合委托接口。 除了明显的
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将尝试绑定一个委托实例,即使在这种情况下我们都关心它是否可以创建委托。)
在这两种情况下,诀窍基本上是要求.NET从MethodInfo创建所需类型的委托,但是如果方法具有错误的签名则返回null而不是抛出exception。 然后针对null进行测试告诉我们代表是否具有正确的签名。
请注意,因为它实际上尝试创建委托,它还将为您处理所有委托方差规则(例如,当方法返回类型兼容但与委托返回类型不完全相同时)。
上述就是C#学习教程:检查针对委托的MethodInfo分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1007487.html