此代码有效,但我想知道这是否是好的解决方案?这个使用表达式树的解决方案会被认为比 Emit 和 OpCodes 更好吗?
var target = Expression.Lambda(
Expression.Block(
new ParameterExpression[] { },
Expression.Call(
typeof(MessageBox).GetMethod("Show", new[] { typeof(string) }),
Expression.Constant(1.ToString(), typeof(string))
)
),
new ParameterExpression[] { }
);
AssemblyName aName = new AssemblyName("DynamicAssemblyExample");
AssemblyBuilder ab =
AppDomain.CurrentDomain.DefineDynamicAssembly(
aName,
AssemblyBuilderAccess.RunAndSave);
ModuleBuilder mb =
ab.DefineDynamicModule(aName.Name, aName.Name + ".dll");
TypeBuilder tb = mb.DefineType("MyDynamicType", TypeAttributes.Public);
var method = tb.DefineMethod("dynamicMethod", MethodAttributes.Public | MethodAttributes.Static);
target.CompileToMethod(method);