2011-12-05 149 views
13

我想不出如何将自定义属性添加到使用Mono.Cecil能 ,我想添加的属性的方法是这样的:使用mono.cecil添加自定义属性?

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

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

回答

13

这其实很简单。

ModuleDefinition module = ...; 
MethodDefinition targetMethod = ...; 
MethodReference attributeConstructor = module.Import(
    typeof(DebuggerHiddenAttribute).GetConstructor(Type.EmptyTypes)); 

targetMethod.CustomAttributes.Add(new CustomAttribute(attributeConstructor)); 
module.Write(...); 
+0

非常感谢,解决了! – method

+1

@JbEvain +1从我开发这个真棒图书馆。我订阅了您的github更改提要,所以我知道仍在逐步倾注的工作 – sehe

+0

@sehe感谢您的客气话! –

3

这是我拿,

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,而不是构造函数。

+2

这是因为我错了:)我已经更新了我的代码片段。谢谢。 –

+0

干杯 - 我被困在0.5.0或更早版本,所以我不会跳到结论:) – sehe

+0

我有一个最后的问题guyz,:ILProcessor.Append(Instruction.Create(OpCodes.Newarr,));操作数应该是什么? ,我已经添加了ldc指令。 – method