【问题标题】:How can I assign the value selected in a listbox to an enum var?如何将列表框中选择的值分配给枚举变量?
【发布时间】:2013-07-30 17:07:43
【问题描述】:

我想避免以下的笨拙:

private void listBoxBeltPrinters_SelectedIndexChanged(object sender, System.EventArgs e)
{
    string sel = string listBoxBeltPrinters.SelectedItem.ToString();
    if (sel == "Zebra QL220")
    {
        PrintUtils.printerChoice = PrintUtils.BeltPrinterType.ZebraQL220;
    }
    else if (sel == "ONiel")
    {
        PrintUtils.printerChoice = PrintUtils.BeltPrinterType.ONiel;
    }
    else if ( . . .)
}

有没有一种方法可以让我根据列表框选择更优雅或更雄辩地分配给枚举,例如:

PrintUtils.printerChoice = listBoxBeltPrinters.SelectedItem.ToEnum(PrintUtils.BeltPrinterType)?

?

【问题讨论】:

  • 为什么不能直接将enum object添加到ListBox
  • @SriramSakthivel 因为 Enum.ToString 无法正确呈现“Zebra QL220”
  • 您必须以任何一种方式妥协,如果有帮助,请查看我的更新解决方案,否则请随时询问

标签: c# enums listbox .net-1.1


【解决方案1】:

你可以试试这样的

Array values = Enum.GetValues(typeof(BeltPrinterType));//If this doesn't help in compact framework try below code
Array values = GetBeltPrinterTypes();//this should work, rest all same
foreach (var item in values)
{
    listbox.Items.Add(item);
}

private static BeltPrinterType[] GetBeltPrinterTypes()
{
    FieldInfo[] fi = typeof(BeltPrinterType).GetFields(BindingFlags.Static | BindingFlags.Public);
    BeltPrinterType[] values = new BeltPrinterType[fi.Length];
    for (int i = 0; i < fi.Length; i++)
    {
        values[i] = (BeltPrinterType)fi[i].GetValue(null);
    }
    return values;
    }

private void listBoxBeltPrinters_SelectedIndexChanged(object sender, System.EventArgs e)
{
    if(!(listBoxBeltPrinters.SelectedItem is BeltPrinterType))
    {
        return;
    }
    PrintUtils.printerChoice = (BeltPrinterType)listBoxBeltPrinters.SelectedItem;
}

【讨论】:

  • 您无法使用您制作的示例将字符串转换为枚举。它返回错误'不能将'string'类型的表达式转换为'BeltPrinterType'
  • 请尝试我的整个样本,而不仅仅是演员!
  • 那你是对的,也许最好检查SelectedItem是否为BeltPrinterType类型以避免异常
  • 不幸的是,.NET1.1 不接受/理解此代码。在stackoverflow.com/questions/17952900/… 看到我姐姐的问题,看来我可能不得不坚持使用笨拙的方法。
  • @MartijnvanPut in CompactFramework Enum.GetValues 方法本身不受支持
【解决方案2】:

使用 Enum.Parse,您可以将字符串转换为 Enum。

PrintUtils.printerChoice = (PrintUtils.BeltPrinterType)Enum.Parse(typeof(PrintUtils.BeltPrinterType),listBoxeltPrinters.SelectedItem);

还有一个方法 Enum.TryParse 返回一个布尔值,指示解析是否成功。

【讨论】:

  • 这将在 "Zebra QL220" 情况下失败
  • 您可以删除字符串空格以避免该问题。
  • @Martijn:与我对 Sriram 的回答类似,不幸的是,这不会在 .NET 1.1 中编译,因为 Enum 在它们的旧百里香中没有“解析”方法。
  • 根据 msdn 文档,它确实存在于 .NET 1.1 中:msdn.microsoft.com/en-us/library/…
  • 这很奇怪;它是红色的,不是 Intellisenseless 提供的选项,并且会导致编译器错误。想一想,可能是因为这不仅仅是 .NET 1.1(87 光年的历史),还有 CD,因此是一个“简化”版本。
猜你喜欢
  • 2014-09-20
  • 1970-01-01
  • 2016-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-08
相关资源
最近更新 更多