【发布时间】:2015-02-13 16:24:41
【问题描述】:
在下面的代码中,cpy 值的更改不会影响ori 值,因此字符串的行为不像引用类型:
string ori = "text 1";
string cpy = ori;
cpy = "text 2";
Console.WriteLine("{0}", ori);
但是,一个类有不同的行为:
class WebPage
{
public string Text;
}
// Now look at reference type behaviour
WebPage originalWebPage = new WebPage();
originalWebPage.Text = "Original web text";
// Copy just the URL
WebPage copyOfWebPage = originalWebPage;
// Change the page via the new copy of the URL
copyOfWebPage.Text = "Changed web text";
// Write out the contents of the page
// Output=Changed web text
Console.WriteLine ("originalWebPage={0}",
originalWebPage.Text);
谁能告诉我为什么类和字符串之间的行为不同,而它们两者都是引用类型?
【问题讨论】:
-
实际上,不,一个类 not 有不同的行为。您在示例中只是做了两件不同的事情:对于字符串,您将一个新值 (
"text 2") 分配给string变量cpy本身。对于您的类WebPage,您只需为变量copyOfWebPage(引用的实例)的属性(Text)分配一个新值("Changed web text")。 -
在这一行
cpy = "text 2";您正在更改变量cpy引用的字符串。在这一行copyOfWebPage.Text = "Changed web text";中,您不会更改copyOfWebPage引用的对象,而是更改两个变量引用的对象的属性Text。 -
@DLeh 与问题无关。这个问题与不变性有什么关系?
-
@SriramSakthivel:没什么,但都落入同一个陷阱。
-
@DLeh 忘记字符串。即使您使用
StringBuilder,您也会看到相同的输出。因为 OP 正在用新实例修改引用,而不是改变它(字符串不可能)。
标签: c#