C#LINQ NULL检查 [英] C# LINQ NULL check
问题描述
在我的表单上,我想要禁用bt_rent按钮,如果电影没有日期在收回列(日期类型),所以这意味着dvd仍然是不可用于出租:
On my form I want to disable the bt_rent button if the movie has no date in the bringback colum(date type) so it means the dvd is still out and not available for renting:
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))对象引用未设置为
对象的实例。 / em>
Nullreferenceexpection was unhandled by user code (error at:if (j.Bringback==null)) Object reference not set to an instance of an object.
推荐答案
您在 j 本身缺少验证。在这种情况下,似乎没有你想要的名字的DVD,所以理想情况下,如果 j 也是NULL,而不是
You are missing validation on j itself. It seems in this case there is no DVD with the name you're looking for so ideally you should validate if j is NULL as well, instead of
if (j.Bringback==null)
执行以下
if (j != null || (j != null && j.Bringback==null))
所以你检查DVD是否存在,如果是,则第二部分验证基于j本身,如果Bringback为空。
So you are checking if the DVD exists, and if it does, the 2nd part of the validation is based on j itself, and if Bringback is null.
这篇关于C#LINQ NULL检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!