我正在阅读Accelerated C#2010.并且有一些问题
问题1
String的实例是不可变的,因为一旦你创建它们,你就无法改变它们
怎么回事呢.我有一段时间没有使用过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?
Run Code Online (Sandbox Code Playgroud)
问题2
如果在字符串上调用ICloneable.Clone方法,则会得到一个指向与源相同的字符串数据的实例.事实上,ICloneable.Clone只是返回对此的引用
如果这是真的,那就意味着
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?
Run Code Online (Sandbox Code Playgroud)
Hei*_*nzi 13
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?
Run Code Online (Sandbox Code Playgroud)
当然!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?
Run Code Online (Sandbox Code Playgroud)
不,因为你没有修改"string 1".在第2行之后,它看起来像这样:
memory "string 1"
^ ^
| |
stack str1 str2
Run Code Online (Sandbox Code Playgroud)
在第3行之后,它看起来像这样:
memory "string 1" "modified string"
^ ^
| |
stack str1 str2
Run Code Online (Sandbox Code Playgroud)