出於某種原因不明visualstudio
告訴我這個代碼是無法訪問:爲什麼不能在c#中爲空字符串爲null?
int? newInt = null;
string test = newInt.ToString();
if (test == null)
{
//unreachable Code
}
謝謝您的幫助! :)
出於某種原因不明visualstudio
告訴我這個代碼是無法訪問:爲什麼不能在c#中爲空字符串爲null?
int? newInt = null;
string test = newInt.ToString();
if (test == null)
{
//unreachable Code
}
謝謝您的幫助! :)
string test = newInt.ToString();
如果將其轉換爲string
,測試將永遠不會爲空。當你轉換它時,它將變成空字符串。
int? newInt = null;
string test = newInt.ToString();
if (test == "")
{
Console.WriteLine("Hello World"); //Reaches the code
}
因爲:
((int?)null).ToString() == string.Empty
從可爲空的INT返回值是一個空字符串。 if塊中的代碼確實檢查了一個永遠不可能存在的空值。這隻適用於因爲int?
是一個框架類型,並且ToString()
的行爲是已知且不可變的。如果您嘗試使用用戶定義的值類型,則無法創建相同的斷言。
.ToString()
不能允許空值。
您可以使用:
convert.ToString(newInt)
檢查條件是:
"string.IsNullOrEmpty(test))"
It * can *。它*不*。如果設計者已經決定這就是他們想要做的事情,那麼沒有什麼能阻止它返回null。 – Servy
試着運行一下,看看'test'設置爲。但是,如果你做了'newInt?.ToString()',那麼'test'就是'null'。事實上,你可能會問爲什麼它不會拋出一個空引用異常,這有點兒有趣。 – juharr
使用if(string.IsNullOrEmpty(test))代替 –
['Nullable .ToString'](https://msdn.microsoft.com/en-us/library/9hd15ket(v = vs.110))的文檔。 ASPX)指出,如果'HasValue'是'FALSE'(當你設置一個可爲空''到'null'是哪種情況) –
juharr