我正在使用带有 Razor View 的 MVC。在这个特定的 View 中,我正在传递类 Bed
的单个实例。 Bed
有一个属性 string Infection
。现在在这个例子中,我在 View 中定义了一个 bool 值 HasInfection
,我在其他地方使用它来更改显示的内容。这最初声明为
var HasInfection = (Model.Infection.Trim() != "";
并按预期工作。但是,现在有一个用例,其中 Bed
可能为 null。这是第一段代码:
@{
ViewBag.Title = "Edit";
var HasInfection = false;
if (Model != null)
{
HasInfection = Model.Infection.Trim() != "";
} // I get a NRE on this line whenever Model is null
}
我什至尝试了复杂的嵌套 if-else 解决方案,但我仍然在 if
的右大括号上得到 NRE。
if (Model.Infection == null)
{
HasInfection = false;
}
else
{
if (Model.Infection != "")
{
HasInfection = true;
}
else
{
HasInfection = false;
}
}
我已经尝试了 &/&&/|/|| 的所有组合我可以想到没有成功。如果 Model
为 null
或 Model.Infection == ""
,则 HasInfection
应为 false
.
我做错了什么?
编辑
在尝试 var HasInfection = Model != null && !string.IsNullOrWhiteSpace(Model.Infection);
之后(因为 Infection
可能是 ""),我仍然得到一个空引用异常。即使异常在 View 中,问题是否可能在 Controller 中?
public ActionResult EditReservation(int Facility, string Room, string Bed)
{
var BedModel = New Bed();
List<Bed> _b = BedModel.GetBed(Facility, Room, Bed);
Bed result = _b.Where(bed => bed.BedStatus == "R" || bed.BedStatus == "A").FirstOrDefault();
return View("Edit", result);
}
最佳答案
我遇到了同样的问题。
当查看 this 中的第二条评论时问题 我发现我的异常实际上比 NullReferenceException 指向的右括号更远(括号外)35 行。
例如:
if(Model.Infection != null)
{
<p>Some Html</p>
} //given NullReferenceException location
<p>Model.Infection</p> //Actual cause of NullReferenceException since
//here Model.Infection can be null
关于c# - 大括号关闭时出现 NullReferenceException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20146863/