尝试编译此代码,但if语句咳出一个错误:
错误1运算符'=='不能应用于'对象'类型的操作数和..
public enum ShoeType
{
soccer = 0,
jogging=1,
fitness=2
}
class Program
{
static void Main(string[] args)
{
string shoetype = "1";
if (Enum.Parse(typeof(ShoeType), shoetype) == ShoeType.jogging)
{
var test = "gotcha";
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果查看文档,您可以看到该Enum.Parse方法被定义为返回一个Object,因此您必须将结果转换为所需的类型.像这样:
(ShoeType)Enum.Parse(typeof(ShoeType), shoetype)
Run Code Online (Sandbox Code Playgroud)
您还可以使用该TryParse方法并使用布尔结果来查看解析是否成功:
ShoeType type;
if (Enum.TryParse(shoetype, out type) && type == ShoeType.jogging)
{
var test = "gotcha";
}
Run Code Online (Sandbox Code Playgroud)