在 ASP.NET 中使用 C#,我想获取两个文本字段的结果,在按下按钮时将它们相加,并显示结果。但是,如果其中一个或两个字段为空,我不想显示任何结果。
现在,如果两个字段都为空,我会一直得到 0 作为结果。我很确定这是因为两个输入数字( double )被分配了默认值 0。如何检查空字段?
这是我在 Controller 中的方法。
[HttpPost]
public ActionResult French(FrenchModel model, string returnUrl)
{
switch (model.operation)
{
case 1:
model.result = model.numberOne + model.numberTwo;
break;
case 2:
model.result = model.numberOne - model.numberTwo;
break;
case 3:
model.result = model.numberOne * model.numberTwo;
break;
case 4:
model.result = model.numberOne / model.numberTwo;
break;
}
return View(model);
}
最佳答案
double 型是值类型,因此不能分配给 null 或“空”。如果您想要此功能,请尝试使用可为空的 double 值。 Nullable<double>
或 double?
应该可以。
请注意,使用可空值类型时,您需要在使用前检查它是否为空,否则可能会遇到 NullReferenceException
的风险。而double
默认为 0
如果未分配。
关于c# - 不为 double 使用默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6145147/