2010-05-19 16 views

Respuesta

29

Absolutamente - use Type.GetCustomAttributes. Código de ejemplo:

using System; 
using System.ComponentModel; 

[Description("This is a wahala class")] 
public class Wahala 
{  
} 

public class Test 
{ 
    static void Main() 
    { 
     Console.WriteLine(GetDescription(typeof(Wahala))); 
    } 

    static string GetDescription(Type type) 
    { 
     var descriptions = (DescriptionAttribute[]) 
      type.GetCustomAttributes(typeof(DescriptionAttribute), false); 

     if (descriptions.Length == 0) 
     { 
      return null; 
     } 
     return descriptions[0].Description; 
    } 
} 

El mismo tipo de código puede recuperar las descripciones de los otros miembros, tales como campos, propiedades etc.

+1

+1 Simplemente lo convertí en un método de extensión para Object :) –

+0

si puede haber múltiples descripciones, ¿quizás las concatene con nuevas líneas? –

+1

Por cierto, tenga esto en cuenta si realiza un puerto a PCL: http://stackoverflow.com/questions/18912697/system-componentmodel-descriptionattribute-in-portable-class-library/23906297 –

2

Puede utilice la reflexión para leer datos de atributos:

System.Reflection.MemberInfo inf = typeof(Wahala); 
object[] attributes; 
attributes = 
    inf.GetCustomAttributes(
     typeof(DescriptionAttribute), false); 

foreach(Object attribute in attributes) 
{ 
    DescriptionAttribute da = (DescriptionAttribute)attribute; 
    Console.WriteLine("Description: {0}", da.Description); 
} 

Adaptado de here.

+0

¿por qué "foreach"? ¿Hay descripciones múltiples? –

+0

@GeorgeBirbilis - podría haber. – Oded

Cuestiones relacionadas