問題描述
這是有效的 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
為什么第一條語(yǔ)句有效?
Why is the first statement valid?
推薦答案
第一個(gè)工作的原因:
來(lái)自 MSDN:
在字符串連接操作中,C# 編譯器將空字符串視為空字符串,但不會(huì)轉(zhuǎn)換原始空字符串的值.
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.
有關(guān)的更多信息+ 二元運(yùn)算符:
當(dāng)一個(gè)或兩個(gè)操作數(shù)都是字符串類型時(shí),二元 + 運(yùn)算符執(zhí)行字符串連接.
The binary + operator performs string concatenation when one or both operands are of type string.
如果字符串連接的操作數(shù)為空,則替換為空字符串.否則,通過調(diào)用從類型對(duì)象繼承的虛擬 ToString
方法,將任何非字符串參數(shù)轉(zhuǎn)換為其字符串表示.
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.
第二個(gè)錯(cuò)誤的原因是:
null(C# 參考) -null 關(guān)鍵字是表示空引用的文字,不引用任何對(duì)象.null 是引用類型變量的默認(rèn)值.
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.
這篇關(guān)于為什么連接空字符串有效但調(diào)用“null.ToString()"無(wú)效?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!