简体   繁体   English

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

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

At first I tried to write an If-Then-Else statement using a ternary operator . 起初我尝试使用ternary operator编写If-Then-Else statement
It works fine then Just out of curiosity I decided to write the same code using a 它工作正常然后出于好奇我决定使用a编写相同的代码
null-coalescing operator but it doesn't work as expected. 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);
}

If I run the program through the route Mysite/Home/MyAction/8777 everything is perfect and the entered Id number will be shown. 如果我通过Mysite / Home / MyAction / 8777路线运行程序,一切都很完美,输入的Id号码将会显示。

But if I run the program without any Id through the route MySite/Home/MyAction nothing will happen and MyContetnt will be empty whereas I expect to see " Id has no value " on the screen. 但是,如果我通过MySite / Home / MyAction路线运行程序没有任何Id ,则不会发生任何事情, MyContetnt将为空,而我希望在屏幕上看到“ Id没有价值 ”。

Am I missing something? 我错过了什么吗?

Edit: I am curious that Is it possible to write the code by using ?? 编辑:我很好奇,是否可以通过使用??编写代码? ( null coalescing operator )? (null合并运算符)?

Convert.ToString() results in an Empty string when the conversion has failed. 转换失败时, Convert.ToString()会生成一个空字符串。 So the null coalescing operator won't detect a null but an Empty string 因此,空合并运算符不会检测null,而是检测空字符串

You should use: 你应该使用:

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

Convert.ToString() , when acting on an int? Convert.ToString()Convert.ToString()用于int? will produce either a numerical string (if the int? has a value) or an empty string (otherwise). 将生成数字字符串(如果int?具有值)或空字符串(否则)。

Therefore, it's not producing null , it's producing "" , and "" ?? x == "" 因此,它不会产生null ,它会产生"""" ?? x == "" "" ?? x == "" . "" ?? x == ""

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

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