问题
I want to avoid the kludginess of:
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 ( . . .)
}
Is there a way I can more elegantly or eloquently assign to an enum based on a list box selection, something like:
PrintUtils.printerChoice = listBoxBeltPrinters.SelectedItem.ToEnum(PrintUtils.BeltPrinterType)?
?
回答1:
You could try something like this
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;
}
回答2:
With Enum.Parse you could convert from a string to a Enum.
PrintUtils.printerChoice = (PrintUtils.BeltPrinterType)Enum.Parse(typeof(PrintUtils.BeltPrinterType),listBoxeltPrinters.SelectedItem);
Also there is method Enum.TryParse which returns a bool indicating if the parse is succeeded.
来源:https://stackoverflow.com/questions/17953173/how-can-i-assign-the-value-selected-in-a-listbox-to-an-enum-var