可能重复:
获取Enum值的属性
我有一个带有Description属性的枚举,如下所示:
public enum MyEnum
{
Name1 = 1,
[Description("Here is another")]
HereIsAnother = 2,
[Description("Last one")]
LastOne = 3
}
Run Code Online (Sandbox Code Playgroud)
我找到了一些用于根据Enum检索描述的代码
public static string GetEnumDescription(Enum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes = fi.GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[];
if (attributes != null && attributes.Any())
{
return attributes.First().Description;
}
return value.ToString();
}
Run Code Online (Sandbox Code Playgroud)
这允许我编写如下代码:
var myEnumDescriptions = from MyEnum n in Enum.GetValues(typeof(MyEnum))
select new { ID = (int)n, Name = Enumerations.GetEnumDescription(n) };
Run Code Online (Sandbox Code Playgroud)
我想要做的是,如果我知道枚举值(例如1) - 我该如何检索描述?换句话说,如何将整数转换为"枚举值"以传递给我的GetDescription方法?
在帖子Enum ToString中,描述了一个方法来使用自定义属性,DescriptionAttribute如下所示:
Enum HowNice {
[Description("Really Nice")]
ReallyNice,
[Description("Kinda Nice")]
SortOfNice,
[Description("Not Nice At All")]
NotNice
}
Run Code Online (Sandbox Code Playgroud)
然后,GetDescription使用如下语法调用函数:
GetDescription<HowNice>(NotNice); // Returns "Not Nice At All"
Run Code Online (Sandbox Code Playgroud)
但是,当我想简单地使用枚举值填充ComboBox时GetDescription,这并没有真正帮助我,因为我不能强制ComboBox调用.
我想要的是有以下要求:
(HowNice)myComboBox.selectedItem将返回所选值作为枚举值.NotNice,用户不会看到" Not Nice At All" 而是看到" ".显然,我可以为我创建的每个枚举实现一个新类,并覆盖它ToString(),但这对每个枚举来说都是很多工作,我宁愿避免这样做.
有任何想法吗?
我有一个组合框,我在其中显示一些条目,如:
Equals
Not Equals
Less Than
Greater Than
Run Code Online (Sandbox Code Playgroud)
请注意,这些字符串包含空格.我有一个定义的枚举,它匹配这些条目,如:
enum Operation{Equals, Not_Equals, Less_Than, Greater_Than};
Run Code Online (Sandbox Code Playgroud)
由于不允许空间,我使用了_字符.
现在,有没有办法将给定的字符串自动转换为枚举元素而无需在C#中编写循环或一组if条件?
我有一个包含以下内容的枚举(例如):
在我的代码中,我使用Country.UnitedKingdom,但是如果我将它分配给字符串,我希望将值设置为UK.
这可能吗?
我正在使用MS bot框架,我无法找到表单流中的枚举选项的自定义消息.我尝试过提示属性,但它不起作用.
我想要的是:bot将为用户显示如下选项:
1)是的,我想成为DayNinja!
2)不,我不想解锁流量来实现我的目标.
3)稍后,我将从基础开始
现在,我得到的是:"是","否","后来"
任何帮助将不胜感激谢谢!
