Подтвердить что ты не робот

Получить атрибуты описания на уровне класса

У меня такой класс

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

}

В любом случае, чтобы получить содержимое атрибута Description для класса Wahala?

4b9b3361

Ответ 1

Абсолютно - используйте 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;
    }
}

Такой же код может извлекать описания для других членов, таких как поля, свойства и т.д.

Ответ 3

Вы можете использовать отражение для чтения данных атрибутов:

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

Адаптировано из здесь.