将静态实例字段添加到 Class 并在构造函数中设置为自身

Add Static Instance Field to Class and Set To Self in Constructor

使用 Mono.Cecil 我正在尝试修补 class 以添加静态字段“Instance”并将其设置在构造函数中。它本质上相当于添加以下内容:

public static Class1 Instance;
public Class1() {
    // does normal constructor stuff
    Class1.Instance = this;
}

不过,我不知道引用存在于何处,在查看 OpCodes 后,我找不到如何将引用推入堆栈以将字段 (OpCodes.Stfld) 存储到我的字段定义。

不过,这是我目前所掌握的。

public static void Patch(AssemblyDefinition assembly) {
    TypeDefinition wfcDefinition = assembly.MainModule.Types.First(t => t.Name == "WinFormConnection");
    MethodDefinition wfcConstructor = wfcDefinition.GetConstructors().First(t => t.IsConstructor);

    FieldDefinition instField = new FieldDefinition("Instance", FieldAttributes.Public | FieldAttributes.Static, wfcConstructor.DeclaringType);
    wfcDefinition.Fields.Add(instField);

    ILProcessor proc = wfcConstructor.Body.GetILProcessor();

    // Where does the instance exist within the stack?
    // Instruction pushInstance = proc.Create(OpCodes.?);
    Instruction allocInstance = proc.Create(OpCodes.Stfld, instField);

    // proc.Body.Instructions.Add(pushInstance);
    proc.Body.Instructions.Add(allocInstance);
}

this 始终是该方法的第一个参数,即您需要执行以下操作:

...
  Instruction pushInstance = proc.Create(OpCodes.Ldarg_0);
  proc.Body.Instructions.Add(pushInstance);

  Instruction store = proc.Create(OpCodes.Stsfld, instField);
  proc.Body.Instructions.Add(store);

还要注意你需要使用Stsfld(存储静态字段)而不是Stfld(存储实例字段)