Creating an expression tree that uses a dynamically generated type

I have fully initialized MethodBuilderand EnumBuilder. MethodBuilderpoints to the entry point of the dynamic assembly. It has the following signature:

public static int Main (string [] args) {...}

The assembly generation code works fine, and I can use Reflection.Emitto verify it. Instead of emitting IL, I want to save the target code from the expression tree. He must:

  • declare enum variable
  • set it to
  • write to the console
  • read pause console
  • returns enum value as int32

IDENTIFICATION:

// Intention: Declare string [] args in the expression scope.
var arguments = Expression.Parameter(typeof(string []), "args");
// Intention: var code = default(MyDynamicEnum);
var code = Expression.Variable(builderEnum, "code");
// Intention: code = MyDynamicEnum.Two;
var assign = Expression.Assign(code, Expression.Constant(2, builderEnum));
// Intention: Console.WriteLine(args [0]);
var write = Expression.Call(typeof(Console).GetMethod("WriteLine", new Type [] { typeof(string) }), Expression.ArrayIndex(arguments, Expression.Constant(0, typeof(int))));
// Intention: Console.ReadKey(true);
var read = Expression.Call(typeof(Console).GetMethod("ReadKey", new Type [] { typeof(bool) }), Expression.Constant(true, typeof(bool)));
// Intention: return ((int) code);
var @return = Expression.Constant(2, typeof(int));

// How to combine above expressions and create a function body?
var block = Expression.Block(arguments, code, assign, write, read, @return);
var lambda = Expression.Lambda<Func<string [], int>>(block, new ParameterExpression [] { arguments });

lambda.CompileToMethod(builderMethod); // Error: Variable 'code' of type 'Type: MyDynamicEnum' referenced from scope '', but it is not defined.

GIST. , , , , . MyDynamicEnum , ? .

+4
1

, Expression.Block.

, :

Expression.Block(variables.ToArray(), queue);

ParameterExpression.

0

All Articles