简体   繁体   English

从Action <T>的实例获取Invoke MethodInfo的最安全方法

[英]Safest way to get the Invoke MethodInfo from Action<T>'s Instance

I am currently working on an extension method that facilitates what the question's title suggests. 我目前正在研究一种扩展方法,它可以促进问题标题的建议。

I could, of course. 当然,我可以。 use the GetMetohd("Invoke") method call on the type and be done with it, But something tells me this is not the "safest" way to go. 对类型使用GetMetohd(“Invoke”)方法调用并完成它,但有些东西告诉我这不是“最安全”的方法。 Classes and types may change, including those in the BCL. 类和类型可能会更改,包括BCL中的类和类型。

So I've come up with the following LINQ statement, which works just fine: 所以我想出了以下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();
    }
}

The thing is, even this feels somewhat iffy, since one day Action can change and contain another method with such traits.. even if I add the "HasGenericParameters" constraint, there's no assurance of safety. 事情是,即使这感觉有些不确定,因为有一天Action可以改变并包含具有这些特征的另一种方法..即使我添加“HasGenericParameters”约束,也不能保证安全。

Do you have any ideas regarding a way to obtain the exact MethodInfo instance relevant to 您对获取与之相关的确切MethodInfo实例的方法有任何想法吗?

"Action<T>.Invoke()"

Unless I am misunderstanding your intent, this whole approach seems unnecessary. 除非我误解你的意图,否则这整个方法似乎是不必要的。 You can acquire the MethodInfo for the exact method behind a delegate like so: 您可以获取MethodInfo以获取委托背后的确切方法,如下所示:

Action<Foo> myAction = //get delegate...
MethodInfo theMethod = myAction.Method;

If the Action<T> is wrapped around a specific instance's method, that instance is available from the myAction.Target property. 如果Action<T>包含在特定实例的方法中,则该实例可从myAction.Target属性获得。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM