C#中的字符串引用
c#
由于字符串是 dotnet 中的 ref 类型,当我们更新变量 x 时,y 中也应该有更新?(因为它是 x 的参考值)。下面给出的示例程序,当 x 更新时 y 的值如何不改变?
public void assignment()
{
string x= "hello";
string y=x; // referencing x as string is ref type in .net
x = x.Replace('h','j');
Console.WriteLine(x); // gives "jello" output
Console.WriteLine(y); // gives "hello" output
}
回答
你是正确的,首先,两者x并y引用同一个对象:
+-----------+
y -> | hello |
+-----------+
^
x --------+
现在看看这一行:
x = x.Replace('h','j');
发生以下情况:
-
x.Replace创建一个新字符串(用 j 替换 h)并返回对这个新字符串的引用。+-----------+ +------------+ y -> | hello | | jello | +-----------+ +------------+ ^ x --------+ -
使用
x = ...,您分配x给这个新引用。y仍然引用旧字符串。+-----------+ +------------+ y -> | hello | | jello | +-----------+ +------------+ ^ x --------------------------+
那么,如何做修改就地一个字符串?你没有。C# 不支持就地修改字符串。字符串被故意设计为不可变的数据结构。对于可变的类似字符串的数据结构,请使用StringBuilder:
var x = new System.Text.StringBuilder("hello");
var y = x;
// note that we did *not* write x = ..., we modified the value in-place
x.Replace('h','j');
// both print "jello"
Console.WriteLine(x);
Console.WriteLine(y);