在类级别获取描述属性

在类级别获取描述属性

问题描述:

我有这样的课程

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

}

反正有没有要获取Wahala类的Description属性的内容?

Is there anyway to get the content of the Description attribute for the Wahala class?

绝对-使用Type.GetCustomAttributes.示例代码:

Absolutely - use Type.GetCustomAttributes. Sample code:

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

同类代码可以检索其他成员的描述,例如字段,属性等.

The same kind of code can retrieve descriptions for other members, such as fields, properties etc.