【问题标题】:Add Static Instance Field to Class and Set To Self in Constructor将静态实例字段添加到类并在构造函数中设置为 Self
【发布时间】:2021-09-30 18:05:28
【问题描述】:

使用 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);
}

【问题讨论】:

    标签: c# mono.cecil


    【解决方案1】:

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

    【讨论】:

    • 谢谢你!我之前确实通过使用我试图实现的确切代码创建一个程序集来解决这个问题,而这正是我发现的。
    • 不错。顺便说一句,你总是可以使用cecilifier.me 来帮助你弄清楚如何使用 Mono.Cecil 来实现一些目标(免责声明,我是 cecilifier 的作者 :))
    猜你喜欢
    • 2014-09-16
    • 2011-04-19
    • 1970-01-01
    • 1970-01-01
    • 2011-05-08
    • 2013-03-05
    • 2010-11-11
    • 2019-09-14
    • 1970-01-01
    相关资源
    最近更新 更多