問題描述
這是有效的 C# 代碼
This is valid C# code
var bob = "abc" + null + null + null + "123"; // abc123
這不是有效的 C# 代碼
This is not valid C# code
var wtf = null.ToString(); // compiler error
為什么第一條語句有效?
Why is the first statement valid?
推薦答案
第一個工作的原因:
來自 MSDN:
在字符串連接操作中,C# 編譯器將空字符串視為空字符串,但不會轉換原始空字符串的值.
In string concatenation operations,the C# compiler treats a null string the same as an empty string, but it does not convert the value of the original null string.
有關的更多信息+ 二元運算符:
當一個或兩個操作數都是字符串類型時,二元 + 運算符執行字符串連接.
The binary + operator performs string concatenation when one or both operands are of type string.
如果字符串連接的操作數為空,則替換為空字符串.否則,通過調用從類型對象繼承的虛擬 ToString
方法,將任何非字符串參數轉換為其字符串表示.
If an operand of string concatenation is null, an empty string is substituted. Otherwise, any non-string argument is converted to its string representation by invoking the virtual ToString
method inherited from type object.
如果 ToString
返回 null
,則替換為空字符串.
If ToString
returns null
, an empty string is substituted.
第二個錯誤的原因是:
null(C# 參考) -null 關鍵字是表示空引用的文字,不引用任何對象.null 是引用類型變量的默認值.
null (C# Reference) - The null keyword is a literal that represents a null reference, one that does not refer to any object. null is the default value of reference-type variables.
這篇關于為什么連接空字符串有效但調用“null.ToString()"無效?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!