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

sia*_*mak 2 c# asp.net-mvc nullable null-coalescing

起初我试着写一个If-Then-Else statement使用a ternary operator.
它工作正常然后出于好奇我决定使用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);
}
Run Code Online (Sandbox Code Playgroud)

如果我通过路线Mysite/Home/MyAction/8777运行程序,一切都很完美,输入的Id数字将会显示.

但是,如果我没有任何Id通过MySite/Home/MyAction路线运行程序,那么 什么都不会发生并且MyContetnt将是空的,而我希望在屏幕上看到" Id没有价值 ".

我错过了什么吗?

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

mid*_*pat 6

Convert.ToString()转换失败时导致空字符串.因此,空合并运算符不会检测空值而是检测空字符串

你应该使用:

MyContetnt = Id.HasValue ? System.Convert.ToString(Id.Value) : "Id has no value";
Run Code Online (Sandbox Code Playgroud)