c#字符串是引用类型 - 为什么当我更改引用A的值时,引用B不会改变?

con*_*att 1 .net c# string reference-type

如果.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)

Chr*_*lor 13

这是因为C#字符串是不可变类型,这意味着您无法更改实例的值.

当您更改字符串的值时,您实际上是在创建一个新字符串,并将引用更改为指向新字符串,之后您的两个引用变量不再引用相同的字符串实例,一个引用原始字符串而另一个引用具有新值的新字符串实例.


Upu*_*ara 5

此图像可能对您有所帮助,以便了解该概念.

在此输入图像描述