-1

我想避免以下的笨拙:

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)?

?

4

2 回答 2

1

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

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

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

于 2013-07-30T17:15:18.290 回答
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;
}
于 2013-07-30T17:15:51.850 回答