0

To be more lazy, I just want to write less code but do the same thing, so I did a test. Just want to use some Attribute and use mono.cecil to inject the .dll file with some il code. And the following is the detail: When coding these:

[FillProperty("Counter")]
public int Counter
{
    get;
    set;
}

After injecting, there is the new code generated(By ILSpy)(C# code):

public int Counter
{
     [CompilerGenerated]
     get
     {
         return this.<Counter>k__BackingField;
     }
     [CompilerGenerated]
     set
     {
         if (this.<Counter>k__BackingField != value)
         {
             this.<Counter>k__BackingField = value;
             this.<Counter>k__BackingField.TriggerEvent("Counter");
         }
     }
}

The definition code:

`private int <Counter>k__BackingField;`

can not be seen, but the IL code is fine:

IL_0000: ldarg.0
IL_0001: ldfld int32 AssemblyTest::'<Counter>k__BackingField'
IL_0006: ldarg.1
IL_0007: beq IL_0023

IL_000c: ldarg.0
IL_000d: ldarg.1
IL_000e: stfld int32 AssemblyTest::'<Counter>k__BackingField'
IL_0013: ldarg.0
IL_0014: ldfld int32 AssemblyTest::'<Counter>k__BackingField'
IL_0019: ldstr "Counter"
IL_001e: callvirt void ['Assembly-CSharp']ExMethod::TriggerEvent<int32>(!!0, string)

IL_0023: ret

And the definition code is fine too:

.field private int32 '<Counter>k__BackingField'
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = (
    01 00 00 00
)

But when I run the injected code, it throws an exception as: "NullReferenceException: Object reference not set to an instance of an object AssemblyTest.set_Counter (Int32 value)". So is there anyone who can give me some tips.

AGB
  • 2,230
  • 1
  • 14
  • 21

1 Answers1

0

The method void ['Assembly-CSharp']ExMethod::TriggerEvent<int32>(!!0, string) is an extension method, therefore it is static. Calls to static methods are made using OpCodes.Call. Switch Callvirt to Call and it should fix your issue.

Mr Anderson
  • 2,200
  • 13
  • 23