如何使用 mono.cecil 添加没有默认构造函数的自定义属性



这个问题与这个问题有关,但不是重复的。Jb 在那里发布,要添加自定义属性,以下代码片段将起作用:

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

使用类似的东西,但添加一个自定义属性,其构造函数在其(唯一)构造函数中接受两个字符串参数,我想为这些参数指定值(显然)。谁能帮忙?

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

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"));

下面介绍如何设置自定义属性的命名参数,该参数完全绕过使用其构造函数的属性值的设置。请注意,您不能直接设置 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);

相关内容

最新更新