开发者

Help with enums and Enum.Parse

I'm new to enum.

I've got this enum:

public enum Categories
{
    Animals,
    Animations,
    Accessories,
    Apearance,
    Clothing,
    Gadgets,
    Land,
    Scr开发者_Python百科ipts,
    Vehicles,
    Weapons,
    Other
}

Then I have this variable: private Categories Category; I'm trying to parse user input (string) so that Category will be equal to the right enum.

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

And I get this Error:

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

I hope you understand what I'm trying to say.


To get the Type object to use with a method like Enum.Parse(), use the typeof operator with the type name. You also need to perform a cast from object (which it returns) to your enum:

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


Pass typeof(Categories) instead of Categories and add a cast, like this:

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

This assumes that this.Category is of type Categories and is required because Enum.Parse returns a value of type, object.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜