IL 与塞西尔的评论

IL comments with cecil

是否可以使用单声道 Cecil 来获取和设置 IL 注释?我正在尝试使用修补程序向程序集添加注释,这样如果修补程序在文件上两次获得 运行,它就可以访问注释并避免进行两次更改。

不,您不能向方法主体添加注释。

但是您可以通过将它们作为自定义属性添加到第一个 运行 来将您的信息保存在元数据中。当您需要复杂数据时,可能会有点棘手,因为 types in custom attributes are limited to:

  • One of the following types: bool, byte, char, double, float, int, long, short, string.
  • The type object.
  • The type System.Type.
  • An enum type, provided it has public accessibility and the types in which it is nested (if any) also have public accessibility (Section 17.2).
  • Single-dimensional arrays of the above types.

但是当你有点创意时它应该是可行的,例如当它足以在更改后标记方法体中的偏移量时你可以添加这样的元数据:

public class C
{
    [TypeOneChanges(new uint[] { 0, 16, 124 })]
    [TypeTwoChanges(new uint[] { 5, 10 })]
    public void M() { }
}

[AttributeUsage(System.AttributeTargets.Method)]
class RemarkableOffsetAttribute : Attribute
{
    public uint[] Offsets { get; }

    public RemarkableOffsetAttribute(uint[] offsets)
    {
        Offsets = offsets;
    }
}

class TypeOneChangesAttribute : RemarkableOffsetAttribute
{
    public TypeOneChangesAttribute(uint[] offsets) : base(offsets) { }
}

class TypeTwoChangesAttribute : RemarkableOffsetAttribute
{
    public TypeTwoChangesAttribute(uint[] offsets) : base(offsets) { }
}