LambdaExpression.CompileToMethod无法与System.Type一起使用?

Pet*_*tru 3 c# compiler-construction expression-trees

我正在尝试制作一种编程语言。尝试将lambda编译为模块时,更确切地说,当尝试使用Convert.ChangeType而不是t.Parse从字符串转换为t(某些类型)时,会出现问题。如果我使用LambdaExpression.Compile并在委托上使用DynamicInvoke,则可以使用,但如果我使用CompileToMethod并生成一个模块(abc.exe)并使用Convert.ChangeType进行转换,则在运行模块时会引发异常: System.TypeAccessException未处理消息=通过方法'Foo.Main()'尝试访问类型'System.RuntimeType'失败。


转换方法:

        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));
    }
Run Code Online (Sandbox Code Playgroud)

Ste*_*iel 5

我能够重现您遇到的异常(这是最难的部分:-)。然后,我能够看到更改以下代码是否有所作为:

 Expression.Constant(typeof(T))
Run Code Online (Sandbox Code Playgroud)

至:

 Expression.Constant(typeof(T), typeof(Type))
Run Code Online (Sandbox Code Playgroud)

只需进行一个小的更改,所有这些似乎就可以正常工作。创建类型类型为Constant的常量会使一切变得快乐。