C# 为什么';当我将null合并运算符转换为字符串时,它是否对我的可为null的int起作用?
起初,我尝试使用C# 为什么';当我将null合并运算符转换为字符串时,它是否对我的可为null的int起作用?,c#,asp.net-mvc,nullable,null-coalescing,C#,Asp.net Mvc,Nullable,Null Coalescing,起初,我尝试使用三元运算符编写If-Then-Else语句 它工作得很好,然后出于好奇,我决定使用 null合并运算符,但它不能按预期工作 public System.Web.Mvc.ActionResult MyAction(int? Id) { string MyContetnt = string.Empty; //This line of code works perfectly //MyContent = Id.HasValue ? Id.Value.ToStr
三元运算符编写If-Then-Else语句
它工作得很好,然后出于好奇,我决定使用
null合并运算符
,但它不能按预期工作
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
的情况下运行程序,则不会发生任何事情,myContentnt
将为空,而我希望在屏幕上看到“Id没有值”
我错过什么了吗
编辑:我很好奇,是否可以使用??(空合并运算符)Convert。当转换失败时,ToString()
将导致空字符串。因此,null合并操作符不会检测null,而是检测空字符串
你应使用:
MyContetnt = Id.HasValue ? System.Convert.ToString(Id.Value) : "Id has no value";
Convert.ToString()
在对int?
执行操作时,将生成一个数字字符串(如果int?
有值)或一个空字符串(否则)
因此,它不是生成null
,而是生成“
”和”??x==”
空int被转换为空字符串,而不是空字符串。我会发布一个只有“否”的答案。但那将是拖拉以及太短pSystem.Convert.ToString(Id.Value)
可以简化为Id.ToString()
Correct。但是因为他已经准备好使用Convert.ToString()了,所以我选择保留它way@SriramSakthivel Id.toString()或Id.value.toString()在Id或Id.value为空时引发InvalidOperationExceptionnull@siamak这就是我为什么用这个语句(简写或内联If语句),以确保在调用.ToString或Convert时Id不为null。ToString@siamak我知道,你应该注意到middelpat的答案中有一个对Id.HasValue的检查。