文字字符串赋值会像这样调用String构造函数吗?

mik*_*e00 1 c# string constructor

出于好奇,如果我打电话:

 string txt = "text"; 
Run Code Online (Sandbox Code Playgroud)

它会在幕后调用吗?

 string txt = new String("text".ToCharArray())?
Run Code Online (Sandbox Code Playgroud)

dtb*_*dtb 7

string txt1 = "text"; 
Run Code Online (Sandbox Code Playgroud)

"text"实习池中加载字符串并将其作为引用存储在txt1变量中.

所以,例如,如果你有

string txt2 = "text"; 
string txt3 = "text"; 
Run Code Online (Sandbox Code Playgroud)

然后ReferenceEquals(txt2, txt3) == true,因为两个变量都引用了实习池中的相同字符串对象.

字符串构造函数创建一个新的,非拘留字符串对象.

string txt4 = new String("text".ToCharArray());
Run Code Online (Sandbox Code Playgroud)

所以ReferenceEquals(txt1, txt4) == false.

有一个例外:new String(new char[0])返回""对实习池中字符串对象的引用.