.net - 发出操作码将字段设置为一个值

标签 .net reflection.emit

我正在尝试动态创建代理,因此使用 Emit 进行实现。 因此,当我使用 emit 设置字段时,我还需要将 isDirty 字段 bool 值设置为 true。

我怎样才能做到这一点?

Property Customer
{
  set
  {
    this.customerName = value;
    this.isDirty = true;
  }
}

发出代码:

 FieldBuilder isDirtyField = myTypeBuilder.DefineField("isDirty", typeof(bool), FieldAttributes.Private);                                                              

// Define the "set" accessor method for CustomerName.
            MethodBuilder custNameSetPropMthdBldr =
                myTypeBuilder.DefineMethod("set_CustomerName",
                                           getSetAttr,
                                           null,
                                           new Type[] { typeof(string) });

        ILGenerator custNameSetIL = custNameSetPropMthdBldr.GetILGenerator();

        custNameSetIL.Emit(OpCodes.Ldarg_0);
        custNameSetIL.Emit(OpCodes.Ldarg_1);
        custNameSetIL.Emit(OpCodes.Stfld, customerNameBldr);

        {
            custNameSetIL.EmitWriteLine("Start isDirty");
            ... do stuf here
            custNameSetIL.EmitWriteLine("End isDirty");

        }
        custNameSetIL.Emit(OpCodes.Ret);

只要我不尝试执行 isDirty 字段,这段代码就可以工作,在这个问题上度过了周末,我试图在这个论坛中获得一些帮助。谢谢

//丹尼斯

最佳答案

我相信您想要的 IL 指令的顺序是

custNameSetIL.Emit(OpCodes.Ldarg_0);     // load this
custNameSetIL.Emit(OpCodes.Ldc_I4_1);            // load true (same as integer 1)
custNameSetIL.Emit(OpCodes.Stfld, isDirtyField); // store into isDirty

关于.net - 发出操作码将字段设置为一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6564810/

相关文章:

.net - 将 .NET 表达式树链接到新程序集

.net - 使用多个文件作为资源管理器的参数打开程序一次

c# - DateTime.ParseExact 根本不起作用,为什么?

c# - 不一致的 Reflection.Emit 支持 Mono?

boolean - IL生成器 : How to add boolean to the stack

c# - 方法实现中的正文签名和声明不匹配

c# - 通用 FromEvent 方法

.net - Android:从 .NET soap Web 服务检索 XML 结果

c# - 扩展方法有什么了不起?

.net - CS0012 : The type 'System.Data.Linq.DataContext' is defined in an assembly that is not referenced