<分区>
我有以下枚举
public enum myEnum
{
ThisNameWorks,
This Name doesn't work
Neither.does.this;
}
enum
不可能有“友好名称”吗?
<分区>
我有以下枚举
public enum myEnum
{
ThisNameWorks,
This Name doesn't work
Neither.does.this;
}
enum
不可能有“友好名称”吗?
最佳答案
您可以按照 Yuriy 的建议使用 Description
属性。以下扩展方法可以轻松获取给定枚举值的描述:
public static string GetDescription(this Enum value)
{
Type type = value.GetType();
string name = Enum.GetName(type, value);
if (name != null)
{
FieldInfo field = type.GetField(name);
if (field != null)
{
DescriptionAttribute attr =
Attribute.GetCustomAttribute(field,
typeof(DescriptionAttribute)) as DescriptionAttribute;
if (attr != null)
{
return attr.Description;
}
}
}
return null;
}
你可以这样使用它:
public enum MyEnum
{
[Description("Description for Foo")]
Foo,
[Description("Description for Bar")]
Bar
}
MyEnum x = MyEnum.Foo;
string description = x.GetDescription();
关于c# - 我的枚举可以有友好的名字吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1415140/