2009-10-08 7 views
11

J'ai un aspect comme celui-ci:PostSharp: Les attributs personnalisés sont supprimés lors de l'utilisation OnMethodInvocationAspect

public class MyAttribute : OnMethodInvocationAspect 
{ 
    public int Offset { get; internal set; } 

    public MyAttribute(int offset) 
    { 
     this.Offset = offset; 
    } 

    public override void OnInvocation(MethodInvocationEventArgs eventArgs) 
    { 
     //do some stuff 
    } 
} 

Maintenant, je vais avoir ma classe, et j'ajouter mon attribut il:

class MyClass 
{ 
    [MyAttribute(0x10)] 
    public int MyProp { get; set; } 
} 

Fonctionne très bien. Pourtant, maintenant je veux utiliser la réflexion pour obtenir mon offset; quand je le fais

typeof(MyClass).GetProperty("MyProp").GetCustomAttributes(true); 

Il ne retourne rien. Comment puis-je accéder à ma valeur Offset d'origine (la propriété de mon attribut)?

Répondre

16

Ah, je l'ai fixé cette façon:

d'abord ajouter un attribut à votre définition d'attribut comme:

[MulticastAttributeUsage(MulticastTargets.Method, PersistMetaData=true)] 
public class MyAttribute : OnMethodInvocationAspect 

Et puis je peux appeler la méthode get_ de ma propriété pour obtenir les données que je veux :

 foreach (PropertyInfo pi in typeof(T).GetProperties()) 
     { 
      var entityAttribute = (MyAttribute)(typeof(T).GetMethod("get_" + pi.Name).GetCustomAttributes(typeof(MyAttribute), true).FirstOrDefault()); 
     } 
+1

Hmm ne peut pas accepter ma propre réponse encore :-) Merci pour –

+0

questions et réponses :) –

+0

homme Merci. J'ai eu un problème similaire ... ça m'a dérouté ... –

Questions connexes