簡體   English   中英

C#Enum - 如何比較價值

[英]C# Enum - How to Compare Value

如何比較此枚舉的值

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異常Objet reference not set to an instance of an object是因為您的userProfile為null並且您獲得null屬性。 檢查調試為什么沒有設置。

編輯(感謝@Rik和@KonradMorawski):

也許你以前可以做一些檢查:

if(userProfile!=null)
{
}

要么

if(userProfile==null)
{
   throw new ArgumentNullException(nameof(userProfile)); // 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 這不是名稱慣例

您應該在比較之前將字符串轉換為枚舉值。

Enum.TryParse("Retailer", out AccountType accountType);

然后

if (userProfile?.AccountType == accountType)
{
    //your code
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM