赋值表达式,用于设置动态创建的枚举值

时间:2014-07-24 13:04:14

标签: c# .net reflection enums expression-trees

我有以下枚举:

[Flags]
public enum MyEnum
{
    None = 0,
    Value1 = 1,
    Value2 = 2,
}

此枚举是使用TypeBuilder动态创建的,因此没有编译时引用它作为强类型枚举。

// The variable enumBuilder is fully created and ready for use.
var code = Expression.Variable(enumBuilder, "code");

我现在需要将MyEnum.Value2分配给变量code

// The following line is supposed to do this: code = MyEnum.Value2;
var assign = Expression.Assign(code, ?????);

如何创建评估为MyEnum.Value2的表达式的右侧?

1 个答案:

答案 0 :(得分:1)

Type enumType = enumBuilder.CreateType();
var assign = Expression.Assign(code, Expression.Constant(2, enumType));