【问题标题】:Adding custom attributes using mono.cecil?使用 mono.cecil 添加自定义属性?
【发布时间】:2012-01-13 08:43:27
【问题描述】:

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

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

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

【问题讨论】:

    标签: c# mono.cecil


    【解决方案1】:

    其实很简单。

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

    【讨论】:

    • @JbEvain +1 我开发了那个很棒的库。我订阅了你的 github 更改提要,所以我知道仍在一步一步投入的工作
    • @JbEvain 如果我们想设置自定义属性的一些属性怎么办?
    【解决方案2】:

    这是我的看法,

    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 的 sn-p 略有不同。我不确定那是因为他使用的是新版本的 Cecil 还是因为我错了:)

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

    【讨论】:

    • 干杯 - 我被困在 0.5.0 或更早版本,所以我不会草率下结论 :)
    • 我有一个最后一个问题 Guyz,: ILProcessor.Append( Instruction.Create(OpCodes.Newarr, ));操作数应该是什么? ,我已经添加了ldc指令。
    • @user959615 它需要一个 TypeReference (到数组的元素类型),例如Instruction.Create(OpCodes.Newarr, module.Import(typeof(Object)))) 创建一个新对象[]
    【解决方案3】:

    我想详细说明 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 的Properties 集合中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-04
      • 2012-07-10
      • 1970-01-01
      • 2011-11-28
      • 2023-03-17
      • 1970-01-01
      • 1970-01-01
      • 2015-03-09
      相关资源
      最近更新 更多