使用输出参数从 MethodInfo 创建委托,无需动态调用

fob*_*ame 1 .net c# reflection lambda delegates

我正在尝试从具有输出参数的 MethodInfo 对象获取委托。我的代码如下:

static void Main(string[] args) {

        MethodInfo m = typeof(Program).GetMethod("MyMethod2");

        IEnumerable<Type> paramsTypes = m.GetParameters().Select(p => p.ParameterType);

        Type methodType = Expression.GetDelegateType(paramsTypes.Append(m.ReturnType).ToArray());

        Delegate d = m.CreateDelegate(methodType);

        Action a = (Action)d;

        a();

    }
Run Code Online (Sandbox Code Playgroud)

我得到的是 System.InvalidCastException: Unable to cast object of type Delegate2$1 to type System.Action in the line that do "Action a = (Action)d". 问题是我不知道在 Action 中放入什么类型,因为我知道正确的类型不是 String,它是编译中 String (String&) 的 Output 等价物。

MyMethod2 有一个输出参数,我认为这就是问题所在,因为当我使用 MyMethod 作为输入参数测试它时,它可以工作。

public static void MyMethod2(out String outputParameter) {

        outputParameter = "hey";

    }

public static void MyMethod(String inputParameter) {

  //does nothing 
    
}
Run Code Online (Sandbox Code Playgroud)

另外,我知道如果我使用 Dynamic Invoke 而不是普通的 Delegate 调用会更容易,但我对此不感兴趣,因为我试图提高我的程序的性能。有谁知道如何做到这一点?谢谢

Jon*_*eet 5

这里没有FuncAction可使用out的参数。不过,您可以轻松声明自己的委托类型:

public delegate void OutAction<T>(out T arg)
Run Code Online (Sandbox Code Playgroud)

然后你可以使用

OutAction<string> action = (OutAction) m.CreateDelegate(typeof(OutAction<string>));
Run Code Online (Sandbox Code Playgroud)

您将无法使用,Expression.GetDelegateType因为它仅支持Funcand Action,但OutAction<>如果您需要动态执行,您可以编写自己的等效项以根据参数计算出要使用的正确类型。