[英]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.