[英]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 : 0
到p.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.