2012-04-23 7 views
6

Questa domanda è correlata a this one, ma non è un duplicato. Jb PUBBLICATE che per aggiungere un attributo personalizzato, il seguente frammento avrebbe funzionato:Come aggiungere un attributo personalizzato senza un costruttore predefinito utilizzando mono.cecil

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

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

Vorrei usare qualcosa di simile, ma per aggiungere un attributo personalizzato il cui costruttore prende due parametri stringa nella sua (solo) costruttore, e mi piacerebbe specificare i valori per quelli (ovviamente). Qualcuno può aiutare?

risposta

12

In primo luogo si deve ottenere un riferimento alla versione corretta del costruttore:

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

allora si può semplicemente compilare il attributi personalizzati con argomenti stringa:

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

Veloce come mai Jb - grazie mille per l'aiuto. Troppo veloce per accettare la risposta, che farò tra qualche minuto ... –

+0

Google deve indicizzare SO in tempo reale: sto utilizzando un semplice avviso di google su Mono.Cecil. –

+0

Wow - impressionante. –

2

Ecco come set denominato Parametri di un attributo personalizzato che ignora totalmente l'impostazione di un valore di attributo utilizzando i suoi costruttori. Come nota, non è possibile impostare CustomAttributeNamedArgument.Argument.Value o CustomAttributeNamedArgument.Argument direttamente come se fossero di sola lettura.

Quello che segue è equivalente a impostare - [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); 
Problemi correlati