C#LINQ NULL检查

时间:2014-04-21 08:10:09

标签: c# linq datetime null var

在我的表单上我想要禁用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))对象引用未设置为实例   对象

4 个答案:

答案 0 :(得分:7)

您缺少 j 本身的验证。在这种情况下,似乎没有带有您正在寻找的名称的DVD,所以理想情况下您应该验证 j 是否为NULL,而不是

if (j.Bringback==null)

执行以下操作

if (j != null || (j != null && j.Bringback==null))

因此,您正在检查DVD是否存在,如果存在,则验证的第二部分基于j本身,如果Bringback为空。

答案 1 :(得分:1)

变量j是给定代码中的一种对象租借

<pre>
var j = (from s in db.Rentals where s.Movietitle == (string)listbox1.SelectedValue select s).FirstOrDefault();
</pre>

Chek j为null或不像

<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>

答案 2 :(得分:0)

该例外表示j本身为null,因此在访问j成员之前,您需要检查null是否不是j

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;
}

答案 3 :(得分:0)

这只是accepted answer 撰写的mez的补充

<小时/> 使用C#6.0&#39; null-conditional operator可以将代码重写为:

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)