簡體   English   中英

將靜態實例字段添加到類並在構造函數中設置為自身

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

使用 Mono.Cecil 我試圖修補一個類以添加一個靜態字段“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 (存儲實例字段)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM