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
创建一个新字符串(将 h 替换为 j)并返回对该新字符串的引用。+-----------+ +------------+ 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);
推荐阅读
- nservicebus - 如何将依赖项注入 NServiceBus 管道行为?
- node.js - 安装 expo-cli 的问题
- django - Django+Wordpress+Nginx 反向代理 apache
- angular - Angular RxJS - 无法使冷可观察到热
- python-3.x - FileNotFoundError:[Errno 2] 没有这样的文件或目录:'C:\\Users\\DELL\\coil-20-unproc\\obj1_0.png'
- amazon-web-services - AWS CodePipeline 可以使用 aws-cli 之类的标签进行部署吗?
- php - 如何将 JSON 数据动态插入到 foreach 的 PHP 数组中
- java - 如何在 recyclerview GridView Android Studio 中添加按钮
- disassembly - 如何使用 Cutter 或 Radare2 比较两个 EXE 文件、找出差异并反编译它们?
- python - 如何在 docplex python API 中定义指标约束?