簡體   English   中英

ASP.NET MVC / C#-空合並運算符,類型

[英]ASP.NET MVC / C# - Null Coalescing Operator, Types

我正在嘗試在頁面上創建分頁。 用戶可以選擇每頁顯示的項目數,然后將首選大小保存為cookie。 但是,當我嘗試在querystring參數和cookie之間進行選擇時,發生了錯誤:

    public ActionResult Index(string keyword, int? page, int? size)
    {
        keyword = keyword ?? "";
        page = page ?? 1;

        //Operator "??" cannot be applied to operands of type "int" and  "int"
        size = size ?? Convert.ToInt32(Request.Cookies.Get("StoriesPageSize").Value) ?? 10; 

是什么導致此錯誤? 如何解決?

Convert.ToInt32只返回int ,而不是int? -因此表達式的類型:

size ?? Convert.ToInt32(...)

int類型的。 您不能將非空值類型用作null運算符表達式的第一個操作數-它不能為null,因此永遠不可能使用第二個操作數(在這種情況下為10)。

如果您嘗試使用StoriesPageSize cookie,但不知道它是否存在,則可以使用:

public ActionResult Index(string keyword, int? page, int? size)
{
    keyword = keyword ?? "";
    page = page ?? 1;

    size = size ?? GetSizeFromCookie() ?? 10;
}

private int? GetSizeFromCookie()
{
    string cookieValue = Request.Cookies.Get("StoriesPageSize").Value;
    if (cookieValue == null)
    {
        return null;
    }
    int size;
    if (int.TryParse(cookieValue, CultureInfo.InvariantCulture, out size))
    {
        return size;
    }
    // Couldn't parse...
    return null;
}

如評論中所述,您可以編寫擴展方法以使其更通用:

public static int? GetInt32OrNull(this CookieCollection cookies, string name)
{
    if (cookies == null)
    {
        throw ArgumentNullException("cookies");
    }
    if (name == null)
    {
        throw ArgumentNullException("name");
    }
    string cookieValue = cookies.Get(name).Value;
    if (cookieValue == null)
    {
        return null;
    }
    int size;
    if (int.TryParse(cookieValue, CultureInfo.InvariantCulture, out size))
    {
        return size;
    }
    // Couldn't parse...
    return null;
}

請注意,我已經更改了使用不變文化的代碼-在不變文化中的cookie中傳播信息是有意義的,因為它實際上並不是用戶可見或對文化敏感的。 您還應確保使用不變的區域性保存 cookie。

無論如何,有了擴展方法(在靜態非泛型頂級類中),您可以使用:

size = size ?? Request.Cookies.GetInt32OrNull("StoriesPageSize") ?? 10;

問題在於,第一個操作的結果( size ?? Convert.ToInt32(Request.Cookies.Get("StoriesPageSize").Value) )是一個int。 然后,您可以在此int和另一個int之間使用Null合並運算符,但是由於int不能為null,因此它將失敗。

如果左側不能為null,則使用Null合並運算符沒有意義,因此編譯器會給出錯誤。

關於如何修復它,您可以像這樣重寫它:

size = size ?? (Request.Cookies.Get("StoriesPageSize") != null ? Convert.ToInt32(Request.Cookies.Get("StoriesPageSize").Value) : 10);

暫無
暫無

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

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