C#Enum - 如何比较价值

Val*_*for 30 c# enums

如何比较此枚举的值

public enum AccountType
{
    Retailer = 1,
    Customer = 2,
    Manager = 3,
    Employee = 4
}
Run Code Online (Sandbox Code Playgroud)

我试图在MVC4控制器中比较这个枚举的值,如下所示:

if (userProfile.AccountType.ToString() == "Retailer")
{
    return RedirectToAction("Create", "Retailer");
}
return RedirectToAction("Index", "Home");
Run Code Online (Sandbox Code Playgroud)

我也尝试过这个

if (userProfile.AccountType.Equals(1))
{
    return RedirectToAction("Create", "Retailer");
}
return RedirectToAction("Index", "Home");
Run Code Online (Sandbox Code Playgroud)

在每种情况下,我都得到一个未设置为对象实例的Object引用.

Kam*_*ski 43

用这个

if (userProfile.AccountType == AccountType.Retailer)
{
     ...
}
Run Code Online (Sandbox Code Playgroud)

如果你想从你的AccountType枚举中获取int并进行比较(不知道原因),请执行以下操作:

if((int)userProfile.AccountType == 1)
{ 
     ...
}
Run Code Online (Sandbox Code Playgroud)

Objet reference not set to an instance of an object异常是因为您的userProfile为null并且您获得null属性.检查调试为什么没有设置.

编辑(感谢@Rik和@KonradMorawski):

也许你以前可以做一些检查:

if(userProfile!=null)
{
}
Run Code Online (Sandbox Code Playgroud)

要么

if(userProfile==null)
{
   throw new ArgumentNullException(nameof(userProfile)); // or any other exception
}
Run Code Online (Sandbox Code Playgroud)


Sat*_*pal 8

Enum.Parse如果是字符串,你可以使用like

AccountType account = (AccountType)Enum.Parse(typeof(AccountType), "Retailer")
Run Code Online (Sandbox Code Playgroud)


Taf*_*ari 7

比较:

if (userProfile.AccountType == AccountType.Retailer)
{
    //your code
}
Run Code Online (Sandbox Code Playgroud)

如果要防止NullPointerException,您可以在比较AccountType之前添加以下条件:

if(userProfile != null)
{
    if (userProfile.AccountType == AccountType.Retailer)
    {
       //your code
    }
}
Run Code Online (Sandbox Code Playgroud)

或更短的版本:

if (userProfile !=null && userProfile.AccountType == AccountType.Retailer)
{
    //your code
}
Run Code Online (Sandbox Code Playgroud)


Dhe*_*rik 5

您可以使用扩展方法以较少的代码执行相同的操作.

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

并使用:

if (userProfile.AccountType.isRetailer())
{
    //your code
}
Run Code Online (Sandbox Code Playgroud)

我建议重命名AccountTypeAccount.这不是名称惯例.