6

式ツリーをメインのエントリポイントとしてPEアセンブリにエクスポートしようとしています。式ツリーを構築してラムダ式を取得しました。次に例を示します。

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は私が欠けているものです。

4

1 に答える 1

14

を使用する代わりに、をExpression.Compile使用しますExpression.CompileToMethod(MethodBuilder)

エントリポイントで実行されるコードとして式ツリーを使用して、ディスク上に実行可能ファイルを作成する短いが完全な例:

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");
    }
}
于 2013-03-01T23:20:44.200 に答える