2011-04-26 91 views
2

可能重複描述:
Get Enum from Description attributeC#枚舉與不工作

大家好,我 有和枚舉這樣定義。

public enum SomeType { 
     [Description("One Value")] 
     One, 
     [Description("Two Value")] 
     Two, 
     [Description("Three Value")] 
     Three  
    } 

但是當我嘗試解析字符串這樣

SomeType test = (SomeType)Enum.Parse(typeof(SomeType), "Three Value"); 

我得到EXCETION「請求值‘三大價值’未找到」。這不應該工作嗎?

謝謝

+0

你實際使用'SomeType'? – 2011-04-26 17:27:25

+0

[查看此條目。當然,你需要什麼(http://stackoverflow.com/questions/424366/c-string-enums) – 2011-04-26 17:30:56

回答

1

不,不是。您可以通過枚舉名稱找到枚舉(「一」,「二」,「三」),但不被描述(至少不是這樣)。通過反射也許......

你可能想看看這個:How to get C# Enum description from value?

更新

看看@ KIvanov的評論看這裏:據Get Enum from Description attribute

+0

真正分析應該承認名稱(「三公」)。但不是說明。 – 2011-04-26 17:33:06

+0

我編輯了我的答案。我寫了「不能」,但它是一個錯字。 – 2011-04-26 17:34:05

1

我知道

SomeType test = (SomeType)Enum.Parse(typeof(SomeType), "Three"); 

會做你想做的事

+0

不是,OP想要通過描述獲取Enum,而不是名稱。順便說一句,我沒有downvote。 – 2011-04-26 17:45:55