如何将一些枚举值添加到组合框
在下面的示例中,我想将以“APPLE”开头的口味添加到表单上的组合框中。当枚举具有唯一值时,它可以正常工作;然而,在我的示例中,两个枚举 PINEAPPLE_PEACH 和 APPLE_ORANGE 的值均为 1,这会弄乱结果。
两个具有相同值的枚举是错误的吗?如果是这样,我该如何更改代码以获得一致的结果?
public enum Flavour
{
APPLE_PEACH = 0,
PINEAPPLE_PEACH = 1,
APPLE_ORANGE = 1,
APPLE_BANANA = 3,
PINEAPPLE_GRAPE = 4
}
private void AddFlavours()
{
foreach (Flavour flavour in Enum.GetValues(typeof(Flavour)))
{
string flavourName = Enum.GetName(typeof(Flavour), flavour);
if (flavourName.StartsWith("APPLE"))
{
myComboBox.Items.Add(flavour);
}
}
}
In the following example I would like to add flavours that start with "APPLE" to a ComboBox on a form. When the enums have unique values it works fine; however, in my example two enums PINEAPPLE_PEACH and APPLE_ORANGE both have a value of 1 and this messes up the results.
Is it erroneous to have two enums with the same value and, if so, how can I change my code to get consistent results?
public enum Flavour
{
APPLE_PEACH = 0,
PINEAPPLE_PEACH = 1,
APPLE_ORANGE = 1,
APPLE_BANANA = 3,
PINEAPPLE_GRAPE = 4
}
private void AddFlavours()
{
foreach (Flavour flavour in Enum.GetValues(typeof(Flavour)))
{
string flavourName = Enum.GetName(typeof(Flavour), flavour);
if (flavourName.StartsWith("APPLE"))
{
myComboBox.Items.Add(flavour);
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 Linq,您可以使用以下命令:
With Linq, you may use this:
您可以使用 Enum.GetNames 而不是 GetValues。它会是这样的(未测试):
You can use Enum.GetNames instead of GetValues. It would be something like this (not tested):