Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

emit Opcodes set field to a value

I am trying dynamic create a proxy, so im pleying with Emit. So when I set my field with emit I also need to set a isDirty field boolan to true.

How can I do that ?

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

emit code:

 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);

This code is working, as long im not trying to do the isDirty field, having spent the weekend on this, im trying to get some help in this forum. thx

// dennis

like image 361
Dennis Larsen Avatar asked Jul 03 '11 18:07

Dennis Larsen


Video Answer


1 Answers

I believe that the sequence of IL instructions you want will be

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
like image 165
kvb Avatar answered Sep 26 '22 04:09

kvb