2012-04-23 14 views
6

この質問は、this oneに関連していますが、重複するものではありません。 JBは、カスタム属性を追加するためにそこにそれを掲示し、次のスニペットは動作します:mono.cecilを使用してデフォルトのコンストラクタを使用せずにカスタム属性を追加するには

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

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

を、私は、同様のものを使用したいのですが、そのコンストラクタその(のみ)コンストラクタで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")); 
+0

クイック - ヘルプは非常に感謝します。あまりにも速く私が数分でやる答えを受け入れることができます... –

+0

GoogleはリアルタイムでSOを索引付けする必要があります:私はMono.Cecilで簡単なGoogleアラートを使用しています。 –

+0

すごく印象的。 –

2

は、ここで名前を設定する方法を説明しますカスタム属性のパラメータ。コンストラクタを使用して属性値の設定を完全にバイパスします。メモとして、CustomAttributeNamedArgument.Argument.ValueまたはCustomAttributeNamedArgument.Argumentを読み込み専用として直接設定することはできません。

次は、設定することと同じです - これまでJbのよう [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); 
関連する問題