2011-05-05 52 views
1

我是新來枚舉。幫助使用枚舉和Enum.Parse

我有了這個枚舉:

public enum Categories 
{ 
    Animals, 
    Animations, 
    Accessories, 
    Apearance, 
    Clothing, 
    Gadgets, 
    Land, 
    Scripts, 
    Vehicles, 
    Weapons, 
    Other 
} 

然後,我有這個變量:private Categories Category; 我試圖分析用戶輸入(串),這樣Category將等於正確的枚舉。

this.Category = Enum.Parse(Categories ,cat); 

我得到這個錯誤:

'Product.Categories' is a 'type' but is used like a 'variable' 

我希望你明白我想說什麼。

回答

3

typeof(Categories)代替Categories並添加一個演員,就像這樣:

this.Category = (Categories)Enum.Parse(typeof(Categories), cat); 

這假定this.Category是類型Categories並且是必需的,因爲Enum.Parse返回類型值object

+0

'this.Category'確實被聲明爲這樣:) – BoltClock 2011-05-05 16:52:05

4

要使Type對象與Enum.Parse()這樣的方法一起使用,請使用帶有類型名稱的typeof運算符。您還需要執行從object鑄造(其返回)到您的枚舉:

this.Category = (Categories) Enum.Parse(typeof(Categories), cat); 
+0

要添加到上面的答案,這[MSDN]上也有一個例子(http://msdn.microsoft.com/en-us/library/essfb559.aspx#9ad1524e-346d-4e5d-8637- 88a5cc1ba98a) – Matt 2011-05-05 16:52:05