Create Delegate from MethodInfo with Output Parameters, without Dynamic Invoke

孤街醉人 提交于 2021-01-28 12:00:59

问题


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

    }

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 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 
    
}

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


回答1:


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)

You could then use

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

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.



来源:https://stackoverflow.com/questions/62515454/create-delegate-from-methodinfo-with-output-parameters-without-dynamic-invoke

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!