jeudi 23 mars 2023

Call compile on an Expression that is known as object and I don't have the Types at compile time

I have a method

public static TDest SimpleStuff<TDest>(object obj) where TDest : new()
{
     var objType = obj.GetType();
     var destinationType = typeof(TDest);
     var method = typeof(SimpleMapper).GetMethod("CreateInit", BindingFlags.Static |    BindingFlags.Public, Type.EmptyTypes);
     var genericMethod = method.MakeGenericMethod(objType, destinationType);
     var expressionFuncAsObject = genericMethod.Invoke(typeof(SimpleMapper), null);
      
        ......
    }

expressionFuncAsObject is really Expression<Func<ObjType, TDest>>.

Is there a way the compiler will let me call .Compile on it? I can't cast it to (Expression<Func<ObjType, TDest>>) because the types are only known at runtime.

I tried using Expression.GetFuncType and passing that to Expression.Lambda

var funcType = Expression.GetFuncType(objType , destinationType);
var func = Expression.Lambda(funcType,
                Expression.Parameter(destinationType), Expression.Parameter(objType ) 
                ).Compile();

But I get System.InvalidOperationException: 'variable '' of type 'B' referenced from scope '', but it is not defined'.





Aucun commentaire:

Enregistrer un commentaire