从具有输出参数的MethodInfo创建委托,而无需动态调用 [英] Create Delegate from MethodInfo with Output Parameters, without Dynamic Invoke

查看:80
本文介绍了从具有输出参数的MethodInfo创建委托,而无需动态调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to get a Delegate from a MethodInfo object that has Output Parameters. My code follows:

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();

    }

我得到的是System.InvalidCastException:无法将类型为Delegate2 $ 1的对象强制转换为执行"Action a =(Action)d"的行中的System.Action.事实是,我不知道要在Action中使用哪种类型,因为我知道正确的类型不是String,而是编译时与String(String&)等效的输出.

I'm getting is a System.InvalidCastException: Unable to cast object of type Delegate2$1 to type System.Action in the line that does "Action a = (Action)d". The thing is that I don't know what type to put in Action because I know that the correct type is not String, it is the Output equivalent of String (String&) in compilation.

MyMethod2有一个Output参数,我认为这是问题所在,因为当我使用MyMethod作为Input参数测试它时,它可以工作.

MyMethod2 has an Output parameter, and I think that is where the problem is because when I test this with MyMethod which as an Input parameter, it works.

public static void MyMethod2(out String outputParameter) {

        outputParameter = "hey";

    }

public static void MyMethod(String inputParameter) {

  //does nothing 
    
}

此外,我知道如果使用动态调用而不是常规的Delegate调用会更容易,但是我对此并不感兴趣,因为我正在尝试提高程序的性能.有谁知道如何做到这一点?谢谢

Also, I know it is easier if I use Dynamic Invoke instead of a normal Delegate call but I'm not interested in that because I'm trying to enhance the performance of my program. Does anyone know how to do this? Thank you

推荐答案

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

There is no Func or Action that can use out parameters. You can easily declare your own delegate type though:

public delegate void OutAction<T>(out T arg)

然后您可以使用

OutAction<string> action = (OutAction) m.CreateDelegate(typeof(OutAction<string>));

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

You won't be able to use Expression.GetDelegateType because that only supports Func and Action, but you could write your own equivalent to work out the correct OutAction<> type to use based on the parameters, if you need to do it dynamically.

这篇关于从具有输出参数的MethodInfo创建委托,而无需动态调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆