C#Enum – 如何比较价值
如何比较此枚举的值
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");
在每种情况下,我都得到一个未设置为对象实例的Object引用。
用这个
if (userProfile.AccountType == AccountType.Retailer) { ... }
如果你想从你的AccountType枚举中获取int并进行比较(不知道原因),请执行以下操作:
if((int)userProfile.AccountType == 1) { ... }
Objet reference not set to an instance of an object
exceptionObjet reference not set to an instance of an object
是因为您的userProfile为null并且您获得null属性。 检查调试为什么没有设置。
编辑(感谢@Rik和@KonradMorawski):
也许你以前可以做一些检查:
if(userProfile!=null) { }
要么
if(userProfile==null) { throw new Exception("no userProfile for this user"); // or any other exception }
你可以使用Enum.Parse
,如果它是字符串
AccountType account = (AccountType)Enum.Parse(typeof(AccountType), "Retailer")
比较:
if (userProfile.AccountType == AccountType.Retailer) { //your code }
如果要防止NullPointerException,您可以在比较AccountType之前添加以下条件:
if(userProfile != null) { if (userProfile.AccountType == AccountType.Retailer) { //your code } }
或更短的版本:
if (userProfile !=null && userProfile.AccountType == AccountType.Retailer) { //your code }
您可以使用扩展方法以较少的代码执行相同的操作。
public enum AccountType { Retailer = 1, Customer = 2, Manager = 3, Employee = 4 } static class AccountTypeMethods { public static bool IsRetailer(this AccountType ac) { return ac == AccountType.Retailer; } }
并使用:
if (userProfile.AccountType.isRetailer()) { //your code }
我建议将AccountType
重命名为Account
。 这不是名称惯例 。