首页 > 解决方案 > 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 
}

标签: c#.netstring

解决方案


你是对的,最初,两者都x引用y同一个对象:

       +-----------+
y   -> |   hello   |
       +-----------+
            ^
x   --------+

现在看看这一行:

x = x.Replace('h','j');

会发生以下情况:

  1. x.Replace创建一个字符串(将 h 替换为 j)并返回对该新字符串的引用。

           +-----------+    +------------+
    y   -> |   hello   |    |   jello    |
           +-----------+    +------------+
                ^
    x   --------+
    
  2. 使用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);

推荐阅读