16

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

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

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

4

3 回答 3

16

这实际上很容易。

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

targetMethod.CustomAttributes.Add(new CustomAttribute(attributeConstructor));
module.Write(...);
于 2011-12-05T16:24:28.907 回答
4

这是我的看法,

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

于 2011-12-05T16:31:27.417 回答
1

我想详细说明 Jb Evain 的回答,关于如何将参数传递给属性。对于示例,我使用System.ComponentModel.BrowsableAttribute并将参数的 vlaue 传递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);
}

此外,可以将命名参数添加到Propertiescreated 的集合中CustomAttribute

于 2020-04-26T15:46:27.757 回答