【发布时间】:2013-10-23 08:50:32
【问题描述】:
如何比较这个枚举的值
public enum AccountType
{
Retailer = 1,
Customer = 2,
Manager = 3,
Employee = 4
}
我正在尝试在 MVC4 控制器中比较此枚举的值,如下所示:
if (userProfile.AccountType.ToString() == "Retailer")
{
return RedirectToAction("Create", "Retailer");
}
return RedirectToAction("Index", "Home");
我也试过了
if (userProfile.AccountType.Equals(1))
{
return RedirectToAction("Create", "Retailer");
}
return RedirectToAction("Index", "Home");
在每种情况下,我都会得到一个未设置为对象实例的对象引用。
【问题讨论】:
-
您确定 userProfile 不为空吗?
-
为什么是枚举值的数字?如果您将枚举用作位标志,则枚举往往只需要数字等效项,并且在这种情况下可能会被删除。
-
枚举可以在不转换为字符串的情况下进行比较,异常也可能来自实例 userProfile
-
@Stony 看起来像,我正在查看为什么 userProfile 为空
-
@ValOkafor 据您所知,我添加了代码以防止 userProfile 为 null时运行 if 语句>