在类中添加静态实例字段,并在构造函数中设置为Self



使用Mono。塞西尔,我正试图修补一个类,以添加一个静态字段& &;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);
}

这个总是方法的第一个参数,也就是说,你需要这样做:

...
  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(存储实例字段)

最新更新