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

Eya*_*rry 6 c# linq reflection delegates action

我目前正在研究一种扩展方法,它可以促进问题标题的建议.

当然,我可以.对类型使用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();
    }
}
Run Code Online (Sandbox Code Playgroud)

事情是,即使这感觉有些不确定,因为有一天Action可以改变并包含具有这些特征的另一种方法..即使我添加"HasGenericParameters"约束,也不能保证安全.

您对获取与之相关的确切MethodInfo实例的方法有任何想法吗?

"Action<T>.Invoke()"
Run Code Online (Sandbox Code Playgroud)

Rex*_*x M 5

除非我误解你的意图,否则这整个方法似乎是不必要的.您可以获取MethodInfo以获取委托背后的确切方法,如下所示:

Action<Foo> myAction = //get delegate...
MethodInfo theMethod = myAction.Method;
Run Code Online (Sandbox Code Playgroud)

如果Action<T>它包含在特定实例的方法中,则该myAction.Target属性可以使用该实例.