lundi 22 juin 2020

Create Delegate from MethodInfo with Output Parameters, without Dynamic Invoke

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





Aucun commentaire:

Enregistrer un commentaire