我有一个单独的类,我想获得"Description"属性:
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";
}
出于参数的考虑,我有一个单独的类,我想检索Description。这段代码看起来像:
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属性时遇到了困难。在这一点上,我想知道这是否是正确的方法(即把它放在一个列表中)。
对于获取description属性有什么建议吗?
我不知道你的上下文,但通过阅读你的代码,似乎你会更好的子类化类水果与名称和描述属性:
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."; }
}
除此之外,你的代码似乎是正确的
你拥有的很好;你只需要:
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);
这对我来说是有效的,但是您需要强制转换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";
}