起初我尝试使用三元运算符
编写If-Then-Else语句
。
然后它工作正常 出于好奇,我决定使用
编写相同的代码
null-coalescing operator
但它没有按预期工作。
public System.Web.Mvc.ActionResult MyAction(int? Id)
{
string MyContetnt = string.Empty;
//This line of code works perfectly
//MyContent = Id.HasValue ? Id.Value.ToString() : "Id has no value";
//This line of code dosent show "Id has no value" at all
MyContetnt = (System.Convert.ToString(Id) ?? "Id has no value").ToString();
return Content(MyContetnt);
}
如果我通过路径 Mysite/Home/MyAction/8777 运行程序,一切都完美,输入的 Id
号码将显示.
但是如果我通过路径 MySite/Home/MyAction 运行没有任何 Id
的程序,什么也不会发生,MyContetnt
将为空,而我希望在屏幕上看到“Id 没有值”。
我错过了什么吗?
编辑:我很好奇是否可以使用 ?? 编写代码? (空合并运算符)?
最佳答案
Convert.ToString()
在转换失败时生成空字符串。因此空合并运算符不会检测到空字符串而是空字符串
你应该使用:
MyContetnt = Id.HasValue ? System.Convert.ToString(Id.Value) : "Id has no value";
关于c# - 当我将可空 int 转换为字符串时,为什么 null 合并运算符不对它起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23884984/