繁体   English   中英

使用Mono.Cecil注入属性的自动实现的后备字段

[英]use Mono.Cecil inject the property's auto-implemented backing field

为了更加懒惰,我只想编写更少的代码,但要做同样的事情,所以我做了一个测试。 只想使用一些属性,并使用mono.cecil将il代码注入.dll文件。 以下是详细信息:对这些进行编码时:

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

注入后,将生成新代码(通过ILSpy)(C#代码):

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

定义代码:

`private int <Counter>k__BackingField;`

看不见,但是IL代码很好:

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

并且定义代码也很好:

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

但是,当我运行注入的代码时,它将引发如下异常:“ NullReferenceException:对象引用未设置为对象AssemblyTest.set_Counter(Int32值)的实例”。 有谁可以给​​我一些提示。

方法void ['Assembly-CSharp']ExMethod::TriggerEvent<int32>(!!0, string)是扩展方法,因此是static 使用OpCodes.Call调用静态方法。 Callvirt切换为Call ,它将解决您的问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM