2013-07-30 25 views
-1

我想避免的kludginess:如何將列表框中選定的值分配給枚舉var?

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

+0

你爲什麼不能直接添加'枚舉object'到列表框 –

+0

@SriramSakthivel因爲Enum.ToString不會正確渲染「斑馬QL220」 – Xcelled194

+0

你必須如果有幫助,請檢查我的更新解決方案,否則請隨時詢問 –

回答

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

不能將字符串強制轉換爲您創建的示例。它返回錯誤'不能投入類型'字符串'的表達式來鍵入'BeltPrinterType' –

+0

嘗試我的整個樣本,而不僅僅是投! –

+0

然後你是正確的,也許最好是檢查SelectedItem類型BeltPrinterType以避免例外 –

1

使用Enum.Parse可以將字符串轉換爲Enum。

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

也有是方法Enum.TryParse返回指示布爾如果解析成功時。

+0

這將在''Zebra QL220'案例中失敗 –

+0

您可以刪除字符串空白以避免該問題。 –

+0

@Martijn:與我對Sriram的回答類似,不幸的是,這不會在.NET 1.1中編譯,因爲Enum在他們的舊胸甲中沒有「解析」方法。 –