C#字符串是引用类型 - 为什么当我改变引用的值,参考B不会改变?当我、字符串、类型

2023-09-03 07:20:49 作者:别说我丑你没资本@

如果在.NET中的字符串是引用类型,在下面的code,为什么不字符串2变更为喜字符串1改变后?

 静态无效IsStringReallyAReference()
{
    字符串字符串1 =你好;
    字符串字符串2 =字符串1;

    Console.WriteLine( - 线 - );
    Console.WriteLine(字符串1);
    Console.WriteLine(字符串2);

    字符串1 =喜;

    Console.WriteLine(字符串1);
    Console.WriteLine(字符串2);
    Console.Read();

}

/ *输出:
您好
您好
你好
您好*/
 

解决方案 Spark之处理布尔 数值和字符串类型的数据

这是因为C#字符串是不可变的类型,这意味着你不能改变的实例的值。

当你改变了字符串的值,你实际上是创建一个新的字符串,并改变参考指向之后,你的两个引用变量不再引用相同的字符串实例新的字符串,一指,而其他原始字符串是指用新的价值,新的字符串实例。

If strings in .NET are reference types, in the below code, why doesn't string2 change to "hi" after string1 is changed?

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*/

解决方案

That is because C# strings are immutable types, meaning that you cannot change the value of the instance.

When you change the string's value you are actually creating a new string and changing the reference to point to the new string after which your two reference variables no longer refer to the same string instance, one refers to the original string while the other refers to the new string instance with the new value.

 
精彩推荐
图片推荐