[英]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.