不确定我是否正确获取了Description属性

时间:2014-07-07 14:31:10

标签: c# .net reflection

我有一个单独的课程,我想获得"描述"属性:

public class Fruits
{
    [Description("The green apples are very green.")]  
    public const string Apples= "Green";

    [Description("Sunkist oranges are very sweet.")]  
    public const string Oranges= "Sunkist";

    [Description("Red grapes are make for wine.")]  
    public const string Grapes= "Red";
}

为了论证,我有一个单独的类,我想要检索描述。 所以代码块看起来像:

        Type fruitType = typeof(LotsOfFruits.Fruits);

        FieldInfo[] fields = fruitType.GetFields();

        foreach (var field in fields)
        {
            Console.WriteLine("Name: {0}", field.Name);
            Console.WriteLine("Value: {0}", field.GetRawConstantValue().ToString());
            List<System.Attribute> attr = field.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute)).ToList();
        }

名称和值字段正确拉动。 我很难得到Description属性。 在这一点上,我想知道这是否正确(即将其放入列表中)。

获取描述属性的任何建议或建议?

3 个答案:

答案 0 :(得分:2)

我不知道您的上下文,但通过阅读您的代码,您似乎更好地使用Name和Description属性继承类Fruit:

public abstract class Fruit
{
    public abstract string Name { get; }
    public abstract string Description { get; }
}

public class Apple : Fruit
{
    public string Name { get { return "Apple"; }
    public string Description { get { return "The green apples are very green."; }
}

public class Orange : Fruit
{
    public string Name { get { return "Orange"; }
    public string Description { get { return "Sunkist oranges are very sweet."; }
}

除此之外,您的代码似乎正确。

答案 1 :(得分:2)

你拥有的一切都很好;你所需要的只是:

var attr = (DescriptionAttribute)field.GetCustomAttribute(
    typeof(DescriptionAttribute));
if(attr != null) Console.WriteLine("Desc: {0}", attr.Description);

或者在以后的.NET版本中:

var attr = field.GetCustomAttribute<DescriptionAttribute>();
if(attr != null) Console.WriteLine("Desc: {0}", attr.Description);

答案 2 :(得分:1)

它对我有用,但你需要将DescriptionAttribute转换为基本属性类。此外,我倾向于获得第一个或默认,除非我知道我可能有多个。

class Program
{

    static void Main(string[] args)
    {
        Type fruitType = typeof(Fruits);

        FieldInfo[] fields = fruitType.GetFields();

        foreach (var field in fields)
        {
            Console.WriteLine("Name: {0}", field.Name);
            Console.WriteLine("Value: {0}", field.GetRawConstantValue().ToString());
            var attr = field.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute)).Cast < System.ComponentModel.DescriptionAttribute>().FirstOrDefault();
            Console.WriteLine("Description: {0}", attr.Description);
            Console.ReadLine();
        }
    }
}

public class Fruits
{
    [Description("The green apples are very green.")]  
    public const string Apples= "Green";

    [Description("Sunkist oranges are very sweet.")]  
    public const string Oranges= "Sunkist";

    [Description("Red grapes are make for wine.")]  
    public const string Grapes= "Red";
}