【发布时间】:2018-08-20 04:23:49
【问题描述】:
我最近开始探索 Mono.Cecil。我有一个问题,我很确定对于有此库经验的人来说非常简单。
我想做什么:
- 将给定类型的私有字段添加到 Class1
- 在 Class1 构造函数中初始化这个字段(还没有到这里:))
我的代码是:
public class Tools
{
public void AddField(string fileName)
{
using (ModuleDefinition module = ModuleDefinition.ReadModule(fileName, new ReaderParameters { ReadWrite = true }))
{
TypeDefinition[] types = module.Types.ToArray();
foreach (var type in types)
{
if (type.Name == "Class2")
{
continue;
}
type.Fields.Add(new FieldDefinition("addedField", Mono.Cecil.FieldAttributes.Private, module.ImportReference(typeof(Int32))));
}
module.Write(); // Write to the same file that was used to open the file
}
}
}
完成后,这是我在 ILSpy 中看到的:
.class public auto ansi beforefieldinit ClassLibrary3.Class1
extends [mscorlib]System.Object
{
// Fields
.field private int32 testint
.field private int32 addedField
// Methods
...
testInt 是我自己在使用 Mono.Cecil 处理库之前直接在 C# 中添加的。它与 Mono.Cecil 为 addedField 生成的内容相同。但是,当我尝试使用控制台应用程序加载这个修改后的程序集时,它会抛出 TypeLoadException 说:非静态全局字段。
有什么想法吗?
【问题讨论】:
标签: c# mono.cecil