【问题标题】:string does not act like reference type [duplicate]字符串不像引用类型[重复]
【发布时间】: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#


【解决方案1】:

类的行为与字符串完全一样,只是在你的两个示例中你没有做同样的事情。

WebPage originalWebPage = new WebPage();
originalWebPage.Text = "Original web text";    

WebPage copyOfWebPage = originalWebPage;

//Overwrite the copy variable just like you did before
copyOfWebPage = new WebPage();
copyOfWebPage.Text = "Modified web text";

Console.WriteLine ("originalWebPage={0}", originalWebPage.Text);
Console.WriteLine ("copyOfWebPage={0}", copyOfWebPage.Text);

Run this example

类的例子让你更清楚地知道发生了什么,什么时候做的

string cpy = ori;
cpy = "text 2";

您将ori 的文本复制到cpy,然后立即将该值丢弃,将复制的"text 2" 复制到cpy,您实际上从未“修改”对象cpy 所指的值to,你只是让它指向一个新对象。

【讨论】:

    【解决方案2】:

    尽管strings 是不可变的,但这种情况与此无关。当您将新引用分配给引用类型时,您将丢弃旧引用。在您的第二个示例中,您正在更改对象的属性,因为它们指向相同的位置,所以它们都会受到影响。

    但是当你这样做时

    cpy = "text 2";
    

    这意味着创建一个新字符串并将它的引用存储到cpy中并丢弃cpy的旧引用。

    【讨论】:

      猜你喜欢
      • 2019-04-10
      • 1970-01-01
      • 2020-01-17
      • 1970-01-01
      • 2018-07-31
      • 2010-11-08
      • 2019-12-12
      • 1970-01-01
      • 2011-06-08
      相关资源
      最近更新 更多