我知道字符串实习是什么,以及为什么下面的代码会这样:
var hello = "Hello";
var he_llo = "He" + "llo";
var b = ReferenceEquals(hello, he_llo); //true
或者
var hello = "Hello";
var h_e_l_l_o = new string(new char[] { 'H', 'e', 'l', 'l', 'o' });
var b = ReferenceEquals(hello, he_llo); //false
...或者我以为我做到了,因为在我正在处理的一些代码中出现了一个微妙的错误:
var s = "";
var sss = new string(new char[] { });
var b = ReferenceEquals(s, sss); //True!?
编译器如何知道 sss
实际上是一个空字符串?
最佳答案
如果在字符串构造函数中传递了一个空数组或 null array,则它返回一个空字符串。
它在 reference code. 的注释中指定
// Creates a new string with the characters copied in from ptr. If
// ptr is null, a 0-length string (like String.Empty) is returned.
您还可以使用 null
数组看到相同的结果,例如:
char[] tempArray = null;
var s = "";
var sss2 = new string(tempArray);
var b = ReferenceEquals(s, sss2); //True!?
关于c# - 字符串实习。编译器怎么知道的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41895683/