如果String是引用类型,那么为什么……? [英] If String is a reference type, then why......?

查看:193
本文介绍了如果String是引用类型,那么为什么……?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


如果String是引用类型,那么为什么strOriginal1不能从"Original String2"更改为"Original String3"?

Hi,
If String is a reference type, then why strOriginal1 is not changed from "Original String2" to "Original String3" ?

string strOriginal1 = "Original String1";
 string strOriginal2 = "Original String2";

 strOriginal1 = strOriginal2;

 strOriginal2 = "Original String3";
Console.WriteLine("Value of strOriginal1 at call: {0}", strOriginal1);
Console.WriteLine( "Value of strOriginal2 at call: {0}", strOriginal2 );
Console.ReadLine();



输出:

原始String2
原始String3



Output:

Original String2
Original String3

推荐答案

对于不可变类型(例如字符串),赋值运算符复制内容,而不是创建对同一对象的另一个引用. 因此,
For immutable types (like strings are), the assignment operator copies content instead of creating another reference to the same object.
Therefore
strOriginal1 = strOriginal2;

不会使strOriginal1引用与strOriginal2相同的对象.相反,它们保留当前具有相同值的单独对象.稍后对后者的更改不会影响前者.

doesn''t make strOriginal1 reference the same object as strOriginal2. Instead they stay separate objects which have identical values at the moment. Later changes to the latter don''t affect the former.


字符串是.net中的不可变对象,其值将复制到赋值语句中.

在声明中
Strings are immutable objects in .net and their values are copied in the assignment statements.

In the statement
strOriginal2 = "Original String3";


您正在将strOriginal2分配给指向原始String3"值的新引用.


You are assigning strOriginal2 to a new reference which is pointing to the "Original String3" value.


这篇关于如果String是引用类型,那么为什么……?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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