Delegates 如何将表达式树保存为新的可执行磁盘文件的主入口点?
我正在尝试将表达式树导出到PE程序集作为主入口点。我通过构建表达式树获得了Lambda表达式,例如:Delegates 如何将表达式树保存为新的可执行磁盘文件的主入口点?,delegates,dynamic-assemblies,Delegates,Dynamic Assemblies,我正在尝试将表达式树导出到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, ne
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步是我缺少的 不要只使用
表达式。编译,使用
简短但完整的示例,在磁盘上创建一个可执行文件,表达式树作为入口点中执行的代码:
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");
}
}
使用系统;
运用系统反思;
使用System.Reflection.Emit;
使用System.Linq.Expressions;
班级计划
{
静态void Main()
{
var asmName=新程序集名称(“Foo”);
var asmBuilder=AssemblyBuilder.DefinedDynamicAssembly
(asmName,AssemblyBuilderAccess.RunAndSave);
var moduleBuilder=asmBuilder.definedDynamicModule(“Foo”、“Foo.exe”);
var typeBuilder=moduleBuilder.DefineType(“程序”,TypeAttributes.Public);
var methodBuilder=typeBuilder.DefineMethod(“Main”,
Static,typeof(void),new[]{typeof(string)};
表达式操作=()=>Console.WriteLine(“已执行”);
action.CompileToMethod(methodBuilder);
typeBuilder.CreateType();
asmBuilder.SetEntryPoint(methodBuilder);
asmBuilder.Save(“Foo.exe”);
}
}
希望“PE文件”应该是“汇编”的意思。改为使用CompileToMethod()。@HansPassant,你说得对,一个包含IL的PE文件。DynamicsSembly类不允许你在构造过程中设置入口点吗?这非常有效,谢谢!我使用了我的LambdaExpression
实例来代替您的操作
。