Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have such a class

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

}

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
188 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...