如何用Mono.Cecil为程序集添加继承自Attribute的自定义特性类
解决Mono.Cecil创建特性类时缺少继承System.Attribute的问题
嘿,这个问题很常见——你只是忘了在创建TypeDefinition的时候显式指定基类为System.Attribute啦!Mono.Cecil默认会把新类的基类设为object,所以需要手动关联上Attribute的类型引用。
修改后的完整代码
var assemblyDef = AssemblyDefinition.ReadAssembly(args[0]); // 获取System.Attribute的类型引用,这是关键! var attributeBaseType = assemblyDef.MainModule.TypeSystem.Attribute; // 创建类型时指定基类,同时修正访问修饰符匹配你的目标代码(internal顶级类) var tp = new TypeDefinition( "", "ConfusedByAttribute", Mono.Cecil.TypeAttributes.NotPublic | Mono.Cecil.TypeAttributes.Class | Mono.Cecil.TypeAttributes.BeforeFieldInit, attributeBaseType ); assemblyDef.MainModule.Types.Add(tp); assemblyDef.Write(args[0] + "neW");
关键细节说明
- 基类指定:通过
assemblyDef.MainModule.TypeSystem.Attribute可以直接获取当前模块中System.Attribute的引用,不用手动查找类型,既方便又不容易出错。 - 访问修饰符匹配:你的目标代码是
internal class,对应Mono.Cecil中的TypeAttributes.NotPublic(顶级类的internal访问级别)。如果是嵌套类的internal,要改用TypeAttributes.NestedAssembly。 - 额外属性:加上
BeforeFieldInit是符合C#编译器默认生成的类属性,和你手写代码的编译结果一致。
这样生成的类就会正确继承System.Attribute,和你期望的代码结构完全一致啦!
内容的提问来源于stack exchange,提问作者Roy B.
相关产品推荐
相关产品推荐

