使用Enum描述的属性

时间:2013-04-14 18:45:41

标签: c#

我有一个枚举,想要添加一个描述foreach值。我读了一些关于属性的东西,可以解决我的问题。我尝试从msdn实现解决方案,但没有成功。如果我使用类但不使用枚举值,它可以工作。

有人可能会发布有效的方法吗?

问候

这是msdn解决方案的链接。这就是我尝试做的事情。唯一的区别是我想要使用枚举值。

http://msdn.microsoft.com/de-de/library/aa288454(v=vs.71).aspx

示例:

public enum Color
{
  [Description("This is red")]
  Red,
  [Description("This is blue")]
  Blue
}

如何访问描述以及如何实现描述类/方法?

2 个答案:

答案 0 :(得分:2)

像这样的东西

using System.ComponentModel;

public enum MyColors{
   [Description("Editor Color")]
   White,
   [Description("Errors Color")]
   Red,
   [Description("Comments Color")]
   Green
}

答案 1 :(得分:0)

尝试使用枚举

public enum MyColors{
[Description("Editor Color")]
White,
[Description("Errors Color")]
Red,
[Description("Comments Color")]
Green
}


var type = typeof(MyColors);
var memInfo = type.GetMember(MyColors.White.ToString());
var attributes = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute),
false);
var description = ((DescriptionAttribute)attributes[0]).Description;