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

查看:110
本文介绍了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)
{ 
     ...
}

Objet引用未设置为对象的实例异常是因为您的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 Exception("no userProfile for this user"); // or any other exception
}

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

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