2011-06-23 84 views

回答

7

指的Convert Enum To Dictionary

public static IDictionary<String, Int32> ConvertEnumToDictionary<K>() 
{ 
if (typeof(K).BaseType != typeof(Enum)) 
{ 
    throw new InvalidCastException(); 
} 

return Enum.GetValues(typeof(K)).Cast<Int32>().ToDictionary(currentItem => Enum.GetName(typeof(K), currentItem)); 
} 

然後你就可以使用返回的字典項填寫您的組合框。

請參考下面的還有:

Dictionary enumeration in C#

Enum to dictionary

+0

+1我喜歡這樣! – Dummy01

1

您可以使用:

Enum.GetValues(typeof(MyEnumType)) 

,只是填充從

編輯組合框項目:當然使用refl撓度得到枚舉類型:)

6

可以通過一般的枚舉是這樣的:

private void Method(Enum tEnum) 
{ 
    Enum.GetValues(tEnum.GetType()); 
} 

而且的GetValues會給你是有可能的是枚舉值。

的使用將是一個有點奇怪:

Method(EnumType.Value) 

所以它可能不適合以及其他想法。

3

使用這種方法,你卡恩添加任何枚舉類型這樣的:AddItems(myCombobox, typeof(Options))

public void AddItems (ComboBox cboBox, Type enumType) 
    { 
    cboBox.Items.AddRange(Enum.GetValues (enumType).Cast<object>().ToArray()); 
    } 

    enum Options 
    { 
    Left, Right, Center 
    } 
6

我覺得這是最好的例子來說明:

假設你有一個枚舉:

enum MyEnum 
{ 
    One, 
    Two, 
    Three 
} 

您可以聲明以下方法:

public static void MyEnumMethod(Enum e) 
    { 
     var enumValues = Enum.GetValues(e.GetType()); 

     // you can iterate over enumValues with foreach 
    } 

你會調用它像這樣:

MyEnumMethod(new MyEnum());