![](/img/trans.png)
[英]Get the object from HttpResponseMessage and invoke a method using MethodInfo.Invoke()
[英]Safest way to get the Invoke MethodInfo from Action<T>'s Instance
我目前正在研究一种扩展方法,它可以促进问题标题的建议。
当然,我可以。 对类型使用GetMetohd(“Invoke”)方法调用并完成它,但有些东西告诉我这不是“最安全”的方法。 类和类型可能会更改,包括BCL中的类和类型。
所以我想出了以下LINQ语句,它可以正常工作:
public static class ActionExtensions
{
public static MethodInfo GetInvoke<T>(this Action<T> obj)
{
var actionType = obj.GetType();
var tType= typeof(T);
return (
from methodInfo
in actionType.GetMethods()
let par = methodInfo.GetParameters()
where par.Length == 1 && par[0].ParameterType == tType
select methodInfo
).FirstOrDefault();
}
}
事情是,即使这感觉有些不确定,因为有一天Action可以改变并包含具有这些特征的另一种方法..即使我添加“HasGenericParameters”约束,也不能保证安全。
您对获取与之相关的确切MethodInfo实例的方法有任何想法吗?
"Action<T>.Invoke()"
除非我误解你的意图,否则这整个方法似乎是不必要的。 您可以获取MethodInfo以获取委托背后的确切方法,如下所示:
Action<Foo> myAction = //get delegate...
MethodInfo theMethod = myAction.Method;
如果Action<T>
包含在特定实例的方法中,则该实例可从myAction.Target
属性获得。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.