![](/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.