Checking a MethodInfo against a delegate(针对委托检查 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:针对委托检查 MethodInfo


- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01