2012-04-25 9 views
5

regresan he definido un atributo personalizadoGetCustomAttributes no valora

[AttributeUsage(AttributeTargets.Property)] 
public class FieldAttribute: Attribute 
{ 
    public FieldAttribute(string field) 
    { 
     this.field = field; 
    } 
    private string field; 

    public string Field 
    { 
     get { return field; } 

    } 
} 

mi clase que utiliza el atributo personalizado es la siguiente

[Serializable()] 
public class DocumentMaster : DomainBase 
{ 

    [Field("DOC_CODE")] 
    public string DocumentCode { get; set; } 


    [Field("DOC_NAME")] 
    public string DocumentName { get; set; } 


    [Field("REMARKS")] 
    public string Remarks { get; set; } 


    } 
} 

Pero cuando intento para obtener el valor del atributo personalizado devuelve el objeto nulo

Type typeOfT = typeof(T); 
T obj = Activator.CreateInstance<T>(); 

PropertyInfo[] propInfo = typeOfT.GetProperties(); 

foreach (PropertyInfo property in propInfo) 
{ 

    object[] colName = roperty.GetCustomAttributes(typeof(FieldAttributes), false); 
    /// colName has no values. 
} 

¿Qué me falta?

+2

es 'FieldAttributes' un error tipográfico? debería ser 'FieldAttribute'? ¿'roperty' también es un error tipográfico? –

+0

Además, ¿con qué 'T' lo está llamando? –

+0

Sí, error tipográfico. Use un nombre mejor, ColumnNameAttribute por ejemplo. O simplemente use Linq para SQL, que hace exactamente lo mismo. –

Respuesta

8

typo: debería ser typeof(FieldAttribute). Hay una enumeración de sistema no relacionada llamada FieldAttributes (en System.Reflection, que tiene en sus directivas using, ya que PropertyInfo se resuelve correctamente).

Además, este es un uso más fácil (suponiendo que el atributo no permite duplicados):

var field = (FieldAttribute) Attribute.GetCustomAttribute(
      property, typeof (FieldAttribute), false); 
if(field != null) { 
    Console.WriteLine(field.Field); 
} 
Cuestiones relacionadas