C# 有关枚举和Enum.Parse的帮助

C# 有关枚举和Enum.Parse的帮助,c#,.net,string,class,enums,C#,.net,String,Class,Enums,我是enum的新手 我有这个枚举: public enum Categories { Animals, Animations, Accessories, Apearance, Clothing, Gadgets, Land, Scripts, Vehicles, Weapons, Other } 然后我有一个变量:private Categories 我正在尝试解析用户输入(字符串),以便Category将

我是enum的新手

我有这个枚举:

public enum Categories
{
    Animals,
    Animations,
    Accessories,
    Apearance,
    Clothing,
    Gadgets,
    Land,
    Scripts,
    Vehicles,
    Weapons,
    Other
}
然后我有一个变量:
private Categories
我正在尝试解析用户输入(字符串),以便
Category
将等于正确的枚举

this.Category = Enum.Parse(Categories ,cat);
我得到了这个错误:

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

我希望您理解我想说的。

要获得
类型
对象,以便与
Enum.Parse()之类的方法一起使用,请使用带有类型名称的
类型
操作符。您还需要执行从
对象
(它返回)到枚举的强制转换:

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

要获取要与类似
Enum.Parse()
的方法一起使用的
Type
对象,请将
typeof
运算符与类型名称一起使用。您还需要执行从
对象
(它返回)到枚举的强制转换:

this.Category = (Categories) Enum.Parse(typeof(Categories), cat);
通过
typeof(Categories)
而不是
Categories
并添加一个cast,如下所示:

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

这假设
This.Category
是类型
Categories
,并且是必需的,因为返回类型值,
object

传递
typeof(Categories)
而不是
Categories
,并添加强制转换,如下所示:

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

这假设
This.Category
属于
Categories
类型,并且是必需的,因为返回类型为
object

的值才能添加到上述答案中,还有一个示例可以添加到上述答案中,在
this.Category
上也有一个这样的例子:)
this.Category
确实是这样声明的:)