2014-05-14 140 views
-2

我有以下枚舉:C#字符串枚舉映射

public enum ItemType 
{ 
    Foo =0, 
    Bar =1 
} 

,然後被傳遞到在小寫的方法的字符串。

如何將字符串與我的枚舉進行比較並返回枚舉。

public ItemType Method(string value) 
{ 
    ///compare string to enum here and return Enum 
} 

和該方法接收的值作爲像這樣的參數(注意小寫)

string value = "foo"; /// or value ="bar" 

ItemType type = Method(value) 

回答

-1

你正在尋找方法Enum.TryParse

public ItemType Method(string value) 
{ 
    ItemType item; 
    if(Enum.TryParse(value, true, out item)) return item; 

    else /* throw exception or return defaul value */ 
} 

第二個參數是允許您執行不區分大小寫的搜索。