mercredi 16 décembre 2020

C# reflection, get ref return type from MethodInfo.Invoke

I use a static library class which has a static generic function, with where T : struct clause.

Also, this function returns ref T.

I wanted to use System.Type as parameter to invoke this generic function, so made a helper function which uses reflection.

public static object MyFunction(System.Type t, object[] params)
{
    var name = nameof(MyStaticLibraryClass.RefReturnStaticMethod);
    var method = typeof(MyStaticLibraryClass).GetMethod(name, BindingFlags.Public | BindingFlags.Static);
    var generic = method.MakeGenericMethod(someType);
    object ret = generic.Invoke(null, params);
    return ret;
}

Unfortunately when I use return value ret, it's value type rather than reference to that struct object.

While debugging, I found out that ret is marked as ByRef type of t.

So the question is, how do I use this object ret as ref type? Seems like return ref ret doesn't work...





Aucun commentaire:

Enregistrer un commentaire