С# 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");

В каждом случае я получаю ссылку на объект, не установленную на экземпляр объекта.

Ответы

Ответ 1

используйте этот

if (userProfile.AccountType == AccountType.Retailer)
{
     ...
}

Если вы хотите получить int из вашего перечисления AccountType и сравнить его (не знаете, почему), выполните следующие действия:

if((int)userProfile.AccountType == 1)
{ 
     ...
}

Objet reference not set to an instance of an object Исключением является то, что ваш пользовательский файл null, и вы получаете свойство null. Проверьте в отладке, почему он не установлен.

EDIT (спасибо @Rik и @KonradMorawski):

Возможно, вы можете сделать чек перед:

if(userProfile!=null)
{
}

или

if(userProfile==null)
{
   throw new Exception("no userProfile for this user"); // or any other exception
}

Ответ 2

Comparision:

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
}

Ответ 3

Вы можете использовать Enum.Parse, например, если это строка

AccountType account = (AccountType)Enum.Parse(typeof(AccountType), "Retailer")

Ответ 4

Вы можете использовать методы расширения, чтобы сделать то же самое с меньшим количеством кода.

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. Это не соглашение о названии.