2010-05-19 137 views

回答

29

絕對 - 使用Type.GetCustomAttributes。示例代碼:

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; 
    } 
} 

同類的代碼可以檢索其他成員的描述,如字段,屬性等

+1

+1只要將它轉換爲Object的擴展方法:) – 2012-08-10 19:13:39

+0

如果可以有多個描述,可能將它們與新行連接起來? – 2016-05-10 11:37:47

+1

順便說一句,請記住這一點,如果你移植到PCL:http://stackoverflow.com/questions/18912697/system-componentmodel-descriptionattribute-in-portable-class-library/23906297 – 2016-05-10 11:40:05

2

你可以使用反射來讀取屬性數據:

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); 
} 

改編自here

+0

爲什麼「foreach」?有多種描述? – 2016-05-10 11:21:40

+0

@GeorgeBirbilis - 可能會有。 – Oded 2016-05-10 11:36:16