6

この質問はこれに関連してますが、重複していません。Jbは、カスタム属性を追加するには、次のスニペットが機能することを投稿しました。

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

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

似たようなものを使用したいのですが、コンストラクターがその(唯一の)コンストラクターに2つの文字列パラメーターを受け取るカスタム属性を追加し、それらの値を(明らかに)指定したいと思います。誰か助けてもらえますか?

4

2 に答える 2

12

まず、コンストラクターの適切なバージョンへの参照を取得する必要があります。

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"));
于 2012-04-23T13:14:17.273 に答える
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);
于 2013-09-13T16:29:25.270 に答える