LambdaExpression.CompileToMethod not working with System.Type?

I am trying to make a programming language. The problem arises when trying to compile a lambda into a module, more precisely, when trying to convert from a string to t (some type) using Convert.ChangeType instead of t.Parse. If I use LambdaExpression.Compile and use DynamicInvoke for the delegate, it works, but if I use CompileToMethod and generate a module (abc.exe) and convert using Convert.ChangeType, it throws an exception when the module starts: Error System.TypeAccessException was unhandled Message = An attempt by the 'Foo.Main ()' method to access the 'System.RuntimeType' type failed.


Method used for conversion:

        private static Expression ConvertExpression<T>(Expression exprToConvert)
    {
        Type[] types = new Type[] { typeof(object), typeof(Type) };
        MethodInfo changeTypeMethod = typeof(System.Convert).GetMethod("ChangeType", types);
        Expression convertedExprAsObject = Expression.Call(changeTypeMethod, exprToConvert, Expression.Constant(typeof(T)));      
        return Expression.Convert(convertedExprAsObject, typeof(T));
    }
+3
source share
1

, ( :-)). , :

 Expression.Constant(typeof(T))

 Expression.Constant(typeof(T), typeof(Type))

. .

+4

All Articles