2011-12-05 17 views
13

私はMono.Cecil 私は追加したい属性使用方法にカスタム属性を追加する方法を見つけ出すことはできません、このようなものです:mono.cecilを使用したカスタム属性の追加?

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

は、誰もがカスタム

答えて

13
を属性を追加する方法を知っています

実際にはとても簡単です。

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

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

ありがとう、解決済み! – method

+1

その素晴らしいライブラリを開発するために私から@JbEvain +1。私はgithubの変更フィードを購読していますので、ステップごとにまだ流れている作業を知っています – sehe

+0

@種の言葉をありがとう! –

3

これは私のテイクで、

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のスニペットが若干異なっているに気づきました。私はそれがCecilの新しいバージョンを使用しているか、または私が間違っているためにそうであるかどうかはわかりません:)

私のバージョンのCecilでは、ImportはコンストラクタではなくTypeReferenceを返します。

+2

それは私が間違っていたからです:)私はスニペットを更新しました。ありがとう。 –

+0

乾杯 - 私は0.5.0以前に立ち往生していたので、結論には飛びません。 – sehe

+0

私は最終的な質問guyzを持っています:ILProcessor.Append(Instruction.Create(OpCodes.Newarr、));オペランドはどのようにすべきですか? 、私はすでにldc命令を追加しています。 – method

関連する問題