【问题标题】:Adding instance field to class using Mono.Cecil使用 Mono.Cecil 将实例字段添加到类
【发布时间】:2018-08-20 04:23:49
【问题描述】:

我最近开始探索 Mono.Cecil。我有一个问题,我很确定对于有此库经验的人来说非常简单。

我想做什么:

  1. 将给定类型的私有字段添加到 Class1
  2. 在 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


    【解决方案1】:

    我会在不久前找到解决方案时回答自己,也许有人会觉得它有用。这是造成我痛苦的部分:

    if (type.Name == "Class2")
    {
    continue;
    }
    

    看完这篇文章后: What is the "<Module>" type? 我意识到实际上我正在向&lt;Module&gt; 类型添加一些字段,这给我带来了麻烦。在更改我的逻辑以将新字段添加到指定类之后,它只能按预期工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-09
      • 1970-01-01
      • 1970-01-01
      • 2015-06-05
      • 2013-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多