Get the description attributes At class level

前端 未结 3 904
梦谈多话
梦谈多话 2021-02-05 07:08

I have such a class

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

}

Is there anyway to get the content of the Descript

3条回答
  •  独厮守ぢ
    2021-02-05 07:51

    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.

提交回复
热议问题