我正在尝试将表达式树导出到 PE 程序集作为主要入口点。我通过构建表达式树获得了 Lambda 表达式,例如:
using System.Linq;
using System;
// 1. use expression trees to create a block expression (not shown)
// 2. create a lambda expression:
LambdaExpression exprLambda = Expression.Lambda(exprBlock, new ParameterExpression[0]);
MethodBuilder mbuilder = null;
// 3. ??? Somehow get a method builder instance that works ???
// 4. Compile the lambda using the MethodBuilder instance.
exprLambda.CompileToMethod(mbuilder);
// 5. ??? Somehow get an AssemblyBuilder instance to .Save(..) this to disk. ???
第 3 步和第 5 步是我所缺少的。
而不是仅仅使用Expression.Compile
, use Expression.CompileToMethod(MethodBuilder) http://msdn.microsoft.com/en-us/library/dd728224.aspx.
简短但完整的示例,在磁盘上创建一个可执行文件,并使用表达式树作为入口点中执行的代码:
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Linq.Expressions;
class Program
{
static void Main()
{
var asmName = new AssemblyName("Foo");
var asmBuilder = AssemblyBuilder.DefineDynamicAssembly
(asmName, AssemblyBuilderAccess.RunAndSave);
var moduleBuilder = asmBuilder.DefineDynamicModule("Foo", "Foo.exe");
var typeBuilder = moduleBuilder.DefineType("Program", TypeAttributes.Public);
var methodBuilder = typeBuilder.DefineMethod("Main",
MethodAttributes.Static, typeof(void), new[] { typeof(string) });
Expression<Action> action = () => Console.WriteLine("Executed!");
action.CompileToMethod(methodBuilder);
typeBuilder.CreateType();
asmBuilder.SetEntryPoint(methodBuilder);
asmBuilder.Save("Foo.exe");
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)