如何将列表框中选择的值分配给枚举变量?
我想避免以下问题:
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.Parse,您可以从字符串转换为枚举。
PrintUtils.printerChoice = (PrintUtils.BeltPrinterType)Enum.Parse(typeof(PrintUtils.BeltPrinterType),listBoxeltPrinters.SelectedItem);
还有方法Enum.TryParse返回一个bool,指示解析是否成功。