[英]C# LINQ NULL check
在我的表單上,如果電影在帶回欄(日期類型)中沒有日期,我想禁用bt_rent按鈕,因此這意味着dvd仍不可用並且無法出租:
var j = (from s in db.Rentals where s.Movietitle == (string)listbox1.SelectedValue select s).FirstOrDefault();
if (j.Bringback==null)
{
elerhetotext.Text = "The dvd is not available for renting";
bt_rent.Enabled = false;
}
else
{
elerhetotext.Text = "Rentable";
bt_rent.Enabled = true;
}
我得到的錯誤:
用戶代碼未處理Nullreferenceexpection(錯誤在:if(j.Bringback == null))對象引用未設置為對象的實例。
您缺少對j本身的驗證。 在這種情況下,似乎沒有您要查找的名稱的DVD,因此理想情況下,您還應該驗證j是否為NULL,而不是
if (j.Bringback==null)
請執行下列操作
if (j != null || (j != null && j.Bringback==null))
因此,您要檢查DVD是否存在,如果存在,則驗證的第二部分基於j本身,並且Bringback為null。
Variavle j是給定代碼中的一種對象Rental
<pre>
var j = (from s in db.Rentals where s.Movietitle == (string)listbox1.SelectedValue select s).FirstOrDefault();
</pre>
Chek j為空或不喜歡
<pre>
if (j==null)
{
elerhetotext.Text = "The dvd is not available for renting";
bt_rent.Enabled = false;
}
else
{
elerhetotext.Text = "Rentable";
bt_rent.Enabled = true;
}
</pre>
異常意味着j
本身為null
,因此您需要在訪問j
的成員之前檢查j
不為null
:
if (j == null) {
elerhetotext.Text = "DVD/movie does not exist";
bt_rent.Enabled = false;
} else if (j.Bringback == null) {
elerhetotext.Text = "The dvd is not available for renting";
bt_rent.Enabled = false;
} else {
elerhetotext.Text = "Rentable";
bt_rent.Enabled = true;
}
var j = (from s in db.Rentals where s.Movietitle == (string)listbox1.SelectedValue select s).FirstOrDefault(); // checks whether `j´ is null or `j.Bringback´ is null if (j?.Bringback == null) { elerhetotext.Text = "The dvd is not available for renting"; bt_rent.Enabled = false; } else { elerhetotext.Text = "Rentable"; bt_rent.Enabled = true; }
if (j != null || (j != null && j.Bringback==null))
將被重寫為
if (j?.Bringback == null)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.