c# - 关于C#字符串: Immutablility & Cloning的问题

标签 c#

我正在阅读 Accelerated C# 2010。有几个问题

问题一

Instances of String are immutable in the sense that once you create them, you cannot change them

怎么会这样。我已经有一段时间没有使用 C# 了,而且我才刚刚开始,所以我什至在语法上也可能是错误的。

string str1 = "this is a string"; // i hope my syntax is right 
str1 = "this is a NEW string"; // i think i can do this right? 

问题二

If you call the ICloneable.Clone method on a string, you get an instance that points to the same string data as the source. In fact, ICloneable.Clone simply returns a reference to this

如果这是真的,那就意味着

string str1 = "string 1";
// i hope my syntax is right too. i am really not sure about this
string str2 = str1.Clone(); 
str2 = "modified string"; // will str1 be modified too? 

最佳答案

string str1 = "this is a string"; // i hope my syntax is right 
str1 = "this is a NEW string"; // i think i can do this right? 

当然! string 是一个引用类型(一个指针,如果你想这样看),所以在第 2 行中,你正在创建变量 str1指向内存中的不同(常量)字符串。原始字符串没有改变,只是不再被引用。

string str1 = "string 1";
string str2 = str1.Clone(); // i hope my syntax is right too. i am really not sure about this
str2 = "modified string"; // will str1 be modified too? 

不,因为你没有修改"string 1"。在第 2 行之后,它看起来像这样:

memory            "string 1"
                    ^    ^ 
                    |    |
stack             str1  str2

在第 3 行之后,它看起来像这样:

memory            "string 1"     "modified string"
                      ^              ^
                      |              |
stack                str1           str2

关于c# - 关于C#字符串: Immutablility & Cloning的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3449620/

相关文章:

c# - 如何使用单独的逗号 (,) 绑定(bind)下拉列表中的两列值

C# tabcontrol的tabpage中的文字没有变化

c# - “如果”语句

c# - 关于不同的编码风格/指南

c# - 调用具有未知签名的方法

c# - 如何通过存储过程获取数据表

c# - 如何通过其属性之一对通用 List<T> (当 T 是一个类时)进行排序?

c# - 在最大化和最小化时绘制或隐藏无边框表单的控制框

c# - 使用 JSON.net,在基类上下文中使用时,如何防止序列化派生类的属性?

c# - 自定义 SimpleMembership