lundi 2 juillet 2018

Is it possible to cast Func

I am trying to create an implementation of Autofac-style automatic delegate factories that would work with AOT (specifically, Unity3d and IL2CPP).

Main problem that I ran into is inability to cast from Func<object, object> to Func<T1, TResult> in the runtime.

Is there any way you can do that with reflection, but avoiding generating IL code in the runtime (i.e. without Reflection.Emit)?

Func<object, object> func = delegate (object arg1)
{
    return arg1.ToString() + " bar";
};

Func<string, string> func2;
func2 = (Func<string, string>)func;


Console.WriteLine(func2("foo")); // "foo bar" ? :(
// System.InvalidCastException: Unable to cast object of type 'System.Func`2[System.Object,System.Object]' to type 'System.Func`2[System.String,System.String]'.





Aucun commentaire:

Enregistrer un commentaire