C#字符串是引用类型 - 为什么当我改变引用的值,参考B不会改变? [英] c# strings are reference types - why when i change reference A's value, reference B doesn't change?

查看:445
本文介绍了C#字符串是引用类型 - 为什么当我改变引用的值,参考B不会改变?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

}

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

解决方案

这是因为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.

这篇关于C#字符串是引用类型 - 为什么当我改变引用的值,参考B不会改变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆