我正在阅读 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?
问题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?
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?
Sure! string
是一个引用类型(apointer,如果你想这样看),所以在第 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)