这个问题在这里已有答案:
如何在C#中枚举枚举? 26个答案
public enum Foos
{
A,
B,
C
}
Run Code Online (Sandbox Code Playgroud)
有没有办法循环可能的值Foos?
基本上?
foreach(Foo in Foos)
Run Code Online (Sandbox Code Playgroud) 在帖子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(),但这对每个枚举来说都是很多工作,我宁愿避免这样做.
有任何想法吗?
想象一下,我有一个这样的枚举(仅作为一个例子):
public enum Direction{
Horizontal = 0,
Vertical = 1,
Diagonal = 2
}
Run Code Online (Sandbox Code Playgroud)
我如何编写一个例程来将这些值放入System.Web.Mvc.SelectList中,因为枚举的内容将来会发生变化?我想将每个枚举名称作为选项文本,并将其值作为值文本,如下所示:
<select>
<option value="0">Horizontal</option>
<option value="1">Vertical</option>
<option value="2">Diagonal</option>
</select>
Run Code Online (Sandbox Code Playgroud)
这是迄今为止我能想到的最好的:
public static SelectList GetDirectionSelectList()
{
Array values = Enum.GetValues(typeof(Direction));
List<ListItem> items = new List<ListItem>(values.Length);
foreach (var i in values)
{
items.Add(new ListItem
{
Text = Enum.GetName(typeof(Direction), i),
Value = i.ToString()
});
}
return new SelectList(items);
}
Run Code Online (Sandbox Code Playgroud)
但是,这总是将选项文本呈现为"System.Web.Mvc.ListItem".通过这个调试也告诉我,Enum.GetValues()正在返回'Horizontal,Vertical'等而不是0,1,正如我所期望的那样,这让我想知道Enum.GetName()和Enum之间有什么区别.的GetValue().