我正在阅读 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/