使用mono.cecil添加自定义属性?

我无法想象如何使用Mono.Cecil将自定义属性添加到方法我想要添加的属性是这样的:

.custom instance void [mscorlib]System.Diagnostics.DebuggerHiddenAttribute::.ctor() = ( 01 00 00 00 ) 

有谁知道如何添加自定义属性

这实际上非常简单。

 ModuleDefinition module = ...; MethodDefinition targetMethod = ...; MethodReference attributeConstructor = module.Import( typeof(DebuggerHiddenAttribute).GetConstructor(Type.EmptyTypes)); targetMethod.CustomAttributes.Add(new CustomAttribute(attributeConstructor)); module.Write(...); 

这是我的看法,

 MethodDefinition methodDefinition = ...; var module = methodDefinition.DeclaringType.Module; var attr = module.Import(typeof (System.Diagnostics.DebuggerHiddenAttribute)); var attrConstructor = attr.Resolve().Constructors.GetConstructor(false, new Type[] {}); methodDefinition.CustomAttributes.Add(new CustomAttribute(attrConstructor)); 

我注意到Jb Evain的片段略有不同。 我不确定这是因为他使用的是较新版本的Cecil还是因为我错了:)

在我的Cecil版本中, Import返回TypeReference ,而不是构造函数。