C# 枚举 - 如何比较值 [英] C# Enum - How to Compare Value

查看:96
本文介绍了C# 枚举 - 如何比较值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何比较这个枚举的值

public enum AccountType
{
    Retailer = 1,
    Customer = 2,
    Manager = 3,
    Employee = 4
}

我正在尝试在 MVC4 控制器中比较此枚举的值,如下所示:

I am trying to compare the value of this enum in an MVC4 controller like so:

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

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

In each case I get an Object reference not set to an instance of an object.

推荐答案

使用这个

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

如果您想从 AccountType 枚举中获取 int 并进行比较(不知道为什么),请执行以下操作:

If you want to get int from your AccountType enum and compare it (don't know why) do this:

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

未将对象引用设置为对象的实例 异常是因为您的 userProfile 为 null 并且您正在获取 null 的属性.检查调试为什么没有设置.

Objet reference not set to an instance of an object exception is because your userProfile is null and you are getting property of null. Check in debug why it's not set.

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

EDIT (thanks to @Rik and @KonradMorawski) :

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

Maybe you can do some check before:

if(userProfile!=null)
{
}

if(userProfile==null)
{
   throw new ArgumentNullException(nameof(userProfile)); // or any other exception
}

这篇关于C# 枚举 - 如何比较值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆