【问题标题】:How do I add a custom attribute without a default constructor using mono.cecil如何使用 mono.cecil 添加没有默认构造函数的自定义属性
【发布时间】:2012-05-04 02:20:38
【问题描述】:

此问题与this one 有关,但不是重复的。 Jb 在那里发布要添加自定义属性,以下 sn-p 将起作用:

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

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

我想使用类似的东西,但要添加一个自定义属性,其构造函数在其(唯一)构造函数中采用两个字符串参数,并且我想为那些(显然)指定值。有人可以帮忙吗?

【问题讨论】:

    标签: c# mono.cecil


    【解决方案1】:

    首先,您必须获得对正确版本的构造函数的引用:

    MethodReference attributeConstructor = module.Import(
        typeof(MyAttribute).GetConstructor(new [] { typeof(string), typeof(string) }));
    

    然后您可以简单地使用字符串参数填充自定义属性:

    CustomAttribute attribute = new CustomAttribute(attributeConstructor);
    attribute.ConstructorArguments.Add(
            new CustomAttributeArgument(
                module.TypeSystem.String, "Foo"));
    attribute.ConstructorArguments.Add(
            new CustomAttributeArgument(
                module.TypeSystem.String, "Bar"));
    

    【讨论】:

    • 快如常 Jb - 非常感谢您的帮助。太快了,我无法接受答案,我会在几分钟内完成...
    • Google 必须实时索引 SO:我在 Mono.Cecil 上使用简单的 google 警报。
    • Jb - 如果您有兴趣,我正在开发的突变测试框架位于 Codeplex:ninjaturtles.codeplex.com。到目前为止,它只处理 IL 操作(可能会出现源代码突变),所以 Mono.Cecil 绝对是天赐之物。感谢您为此付出的所有辛勤工作。
    • @DavidM,太棒了,我冒昧地将您的项目添加到 Cecil 用户列表中:github.com/jbevain/cecil/wiki/Users
    • 谢谢 Jb,很高兴有它!
    【解决方案2】:

    以下是如何设置自定义属性的命名参数,它完全绕过使用其构造函数设置属性值。请注意,您不能直接设置 CustomAttributeNamedArgument.Argument.Value 甚至 CustomAttributeNamedArgument.Argument,因为它们是只读的。

    以下相当于设置 - [XXX(SomeNamedProperty = {some value})]

        var attribDefaultCtorRef = type.Module.Import(typeof(XXXAttribute).GetConstructor(Type.EmptyTypes));
        var attrib = new CustomAttribute(attribDefaultCtorRef);
        var namedPropertyTypeRef = type.Module.Import(typeof(YYY));
        attrib.Properties.Add(new CustomAttributeNamedArgument("SomeNamedProperty", new CustomAttributeArgument(namedPropertyTypeRef, {some value})));
        method.CustomAttributes.Add(attrib);
    

    【讨论】:

      猜你喜欢
      • 2012-01-13
      • 2016-07-15
      • 2015-10-30
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      • 2016-07-18
      • 1970-01-01
      • 2012-12-13
      相关资源
      最近更新 更多