c# - 当我将可空 int 转换为字符串时,为什么 null 合并运算符不对它起作用?

标签 c# asp.net-mvc nullable null-coalescing

起初我尝试使用三元运算符编写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/

相关文章:

c# - Sitecore 创建包含字段 [] 的项目

c# - 提高生成列表的性能

c# - Entity Framework 多个结果集、Azure 连接弹性和命令拦截

.net - ASP.NET MVC 应用程序中的单例类或具有静态方法的类

c# - 使用 PHP 和 MVC 将 XML 文件上传到 Web 目录

.net - 使用 CType Int32?到 Int64? - System.InvalidCastException : Specified cast is not valid

c# - 我可以使用 ASP.NET 设置 HTML/电子邮件模板吗?

c# - 在 ASP.NET MVC 应用程序中看不到资源命名空间

c# - 无法将类型 'System.ValueType' 隐式转换为 'int?'

c# - System.Nullable<T> null * int值是什么值?