簡體   English   中英

Nullable類型和.HasValue仍然會拋出Null異常

[英]Nullable type and .HasValue still throws a Null Exception

我有一個類描述存儲的各種電話。 有時, Importance屬性可以為null。 這是班級

public class PhoneTypeListInfo
{
    public string AccountNum { get; set; }
    public int PhoneType { get; set; }
    public string PhoneNum { get; set; }

    public int Importance { get; set; }
}

我已經定義了一個函數,如果電話號碼和帳號與給定的一組值匹配,它將返回PhoneTypeListInfo

    protected PhoneTypeListInfo RetrievePhoneType(string info, string acctNumber)
    {
        PhoneTypeListInfo type = xPhoneTypeList.Where(p => p.PhoneNum == info && p.AccountNum == acctNumber).FirstOrDefault();

        return type;
    }

一切都很好。 我遇到的問題是下面的linq查詢。

List<AlertBasedPhones> xAccountPhones = new List<AlertBasedPhones>();
xAccountPhones = (from x in xAccountStuff
                  where x.Media == "Phone"
                  let p = RetrievePhoneType(x.Info, acct.AccountNumber)
                  let xyz = x.Importance = (p.Importance as int?).HasValue ? p.Importance : 0
                  orderby p.Importance descending
                  select x).ToList();

我上面所做的是嘗試使用具有不同組成的不同類,除了從PhoneTypeListInfo獲取“重要性”屬性。

我的問題最終是,我需要做什么才能允許p.Importance為null,如果它為null則將其設置為0,同時使x.Importance 0。

它不是p.Importannce是null,而是p本身。 這是你需要首先檢查null的事情。 如果您使用的是C#6,可以使用?. 運營商。 你也可以把(p.Importance as int?).HasValue ? p.Importance : 0的邏輯(p.Importance as int?).HasValue ? p.Importance : 0 (p.Importance as int?).HasValue ? p.Importance : 0p.Importance ?? 0 p.Importance ?? 0 結合兩者你得到

List<AlertBasedPhones> xAccountPhones = new List<AlertBasedPhones>();
xAccountPhones = (from x in xAccountStuff
                         where x.Media == "Phone"
                         let p = RetrievePhoneType(x.Info, acct.AccountNumber)
                         let xyz = x.Importance = p?.Importance ?? 0
                         orderby p?.Importance descending
                         select x).ToList();

使用三元運算符。 p.Importance替換為(null==p) ? 0 : p.Importance (null==p) ? 0 : p.Importance

暫無
暫無

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

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