在下面的代码中,cpy值的更改不会影响ori值,因此string的行为不像引用类型:
string ori = "text 1";
string cpy = ori;
cpy = "text 2";
Console.WriteLine("{0}", ori);
Run Code Online (Sandbox Code Playgroud)
但是,一个类有不同的行为:
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);
Run Code Online (Sandbox Code Playgroud)
有人可以告诉我为什么类和字符串之间的行为是不同的,而其中两个是引用类型?
即使strings是不可改变的,这种情况与此无关.当您为引用类型分配新引用时,您将丢弃旧引用.在第二个示例中,您正在更改对象的属性,因为它们指向相同的位置,它们都受到影响.
但是,当你这样做
cpy = "text 2";
Run Code Online (Sandbox Code Playgroud)
这意味着创建一个新的字符串并将其引用存储cpy并丢弃旧的引用cpy.