2009-10-08 16 views
11

Tengo algún aspecto de esta manera:PostSharp: Los atributos personalizados se eliminan cuando se utiliza 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 
    } 
} 

Ahora estoy teniendo mi clase, y añadir mi atributo a ella:

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

Funciona todo bien. Sin embargo, ahora quiero usar el reflejo para obtener mi compensación; cuando lo hago

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

Devuelve nada. ¿Cómo puedo acceder a mi valor de compensación original (la propiedad en mi atributo)?

Respuesta

16

Ah, fijado de esta manera:

Primera añadir un atributo a su definición de atributo como:

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

Y entonces me puede llamar al método get_ de mi propiedad para obtener los datos que yo quiero :

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

Hmm no puede aceptar mi propia respuesta todavía :-) –

+0

Gracias por preguntas y respuestas :) –

+0

Gracias hombre. Tuve un problema similar ... me confundía muchísimo ... –

Cuestiones relacionadas