繁体   English   中英

当我将它转换为字符串时,为什么null合并运算符不能在我的可空int上运行?

[英]Why doesn't the null coalescing operator work on my nullable int when I convert it to a string?

起初我尝试使用ternary operator编写If-Then-Else statement
它工作正常然后出于好奇我决定使用a编写相同的代码
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没有价值 ”。

我错过了什么吗?

编辑:我很好奇,是否可以通过使用??编写代码? (null合并运算符)?

转换失败时, Convert.ToString()会生成一个空字符串。 因此,空合并运算符不会检测null,而是检测空字符串

你应该使用:

MyContetnt = Id.HasValue ? System.Convert.ToString(Id.Value) : "Id has no value";

Convert.ToString()Convert.ToString()用于int? 将生成数字字符串(如果int?具有值)或空字符串(否则)。

因此,它不会产生null ,它会产生"""" ?? x == "" "" ?? x == ""

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM