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

C# 使用mono.cecil添加自定义属性?,c#,mono.cecil,C#,Mono.cecil,我不知道如何使用Mono.Cecil向方法添加自定义属性 我想添加的属性如下: .custom instance void [mscorlib]System.Diagnostics.DebuggerHiddenAttribute::.ctor() = ( 01 00 00 00 ) 有人知道如何添加自定义属性吗?其实很简单 ModuleDefinition module = ...; MethodDefinition targetMethod = ...; MethodReference a

我不知道如何使用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
,而不是构造函数。

我想详细说明Jb Evain关于如何将参数传递给属性的答案。对于示例,我使用了
System.ComponentModel.BrowsableAttribute
,并将
browsable
参数的值传递给其构造函数:

void AddBrowsableAttribute(
    ModuleDefinition module,
    Mono.Cecil.ICustomAttributeProvider targetMember, // Can be a PropertyDefinition, MethodDefinition or other member definitions
    bool browsable)
{
    // Your attribute type
    var attribType = typeof(System.ComponentModel.BrowsableAttribute);
    // Find your required constructor. This one has one boolean parameter.
    var constructor = attribType.GetConstructors()[0];
    var constructorRef = module.ImportReference(constructor);
    var attrib = new CustomAttribute(constructorRef);
    // The argument
    var browsableArg =
        new CustomAttributeArgument(
            module.ImportReference(typeof(bool)),
            browsable);
        attrib.ConstructorArguments.Add(browsableArg);
    targetMember.CustomAttributes.Add(attrib);
}

此外,命名参数可以添加到所创建的
CustomAttribute

Cheers的
Properties
集合中-我被困在0.5.0或更早版本中,因此我不会直接得出结论:)我还有最后一个问题:ILProcessor.Append(Instruction.Create(OpCodes.Newarr,);操作数应该是什么,我已经添加了ldc指令。@user959615它需要一个类型引用(数组的元素类型),例如
instruction.Create(opcode.Newarr,module.Import(typeof(Object)))
从我这里创建一个新对象[]@JbEvain+1来开发这个很棒的库。我已经订阅了你的github更改订阅源,因此我知道仍在一步步进行的工作step@JbEvain如果要设置自定义属性的某些属性,该怎么办?