如何将列表框中选择的值分配给枚举变量

本文关键字:分配 枚举变量 选择 列表 | 更新日期: 2023-09-27 18:25: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)?

如何将列表框中选择的值分配给枚举变量

您可以尝试类似的

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;
}

使用Enum.Passe可以将字符串转换为Enum。

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

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