检查 system.nullreferenceexception
Check system.nullreferenceexception
我的代码如下:
@{var UName = ((IEnumerable<Pollidut.ViewModels.ComboItem>)ViewBag.UnionList).FirstOrDefault(x => x.ID == item.UNION_NAME_ID).Name;<text>@UName</text>
如果 ViewBag.UnionList 为空,那么它会通过 system.nullreferenceexception.How 来检查和验证吗?
好吧,如果序列为空,您正在调用 FirstOrDefault
- 即 returns null(或者更确切地说,元素类型的默认值)。所以你可以用一个单独的语句检测到:
@{var sequence = (IEnumerable<Pollidut.ViewModels.ComboItem>)ViewBag.UnionList;
var first = sequence.FirstOrDefault(x => x.ID == item.UNION_NAME_ID);
var name = first == null ? "Some default name" : first.Name; }
<text>@UName</text>
在 C# 6 中,使用 null 条件运算符更容易,例如
var name = first?.Name ?? "Some default name";
(这里略有不同 - 如果 Name
returns 为 null,在后面的代码中你会得到默认名称;在前面的代码中你不会。)
首先,你不应该在视图中做这种工作。它属于控制器。所以 cshtml 应该只是:
<text>@ViewBag.UName</text>
然后在控制器中,使用如下内容:
var tempUnion = UnionList.FirstOrDefault(x => x.ID == item.UNION_NAME_ID);
ViewBag.UName = tempUnion == null ? "" : tempUnion.Name;
我的代码如下:
@{var UName = ((IEnumerable<Pollidut.ViewModels.ComboItem>)ViewBag.UnionList).FirstOrDefault(x => x.ID == item.UNION_NAME_ID).Name;<text>@UName</text>
如果 ViewBag.UnionList 为空,那么它会通过 system.nullreferenceexception.How 来检查和验证吗?
好吧,如果序列为空,您正在调用 FirstOrDefault
- 即 returns null(或者更确切地说,元素类型的默认值)。所以你可以用一个单独的语句检测到:
@{var sequence = (IEnumerable<Pollidut.ViewModels.ComboItem>)ViewBag.UnionList;
var first = sequence.FirstOrDefault(x => x.ID == item.UNION_NAME_ID);
var name = first == null ? "Some default name" : first.Name; }
<text>@UName</text>
在 C# 6 中,使用 null 条件运算符更容易,例如
var name = first?.Name ?? "Some default name";
(这里略有不同 - 如果 Name
returns 为 null,在后面的代码中你会得到默认名称;在前面的代码中你不会。)
首先,你不应该在视图中做这种工作。它属于控制器。所以 cshtml 应该只是:
<text>@ViewBag.UName</text>
然后在控制器中,使用如下内容:
var tempUnion = UnionList.FirstOrDefault(x => x.ID == item.UNION_NAME_ID);
ViewBag.UName = tempUnion == null ? "" : tempUnion.Name;