String是一种引用类型,即使它具有值类型的大多数特性,例如是不可变的并且具有==重载以比较文本而不是确保它们引用相同的对象.
为什么字符串不是一个值类型呢?
如果.NET中的字符串是引用类型,在下面的代码中,为什么string1更改后string2不会更改为"hi"?
static void IsStringReallyAReference()
{
string string1 = "hello";
string string2 = string1;
Console.WriteLine("-- Strings --");
Console.WriteLine(string1);
Console.WriteLine(string2);
string1 = "hi";
Console.WriteLine(string1);
Console.WriteLine(string2);
Console.Read();
}
/*Output:
hello
hello
hi
hello*/
Run Code Online (Sandbox Code Playgroud)