首页 > 解决方案 > StringBuilder("...").ToString() 和 new String() 的行为不同。为什么?

问题描述

在以下测试中:str == str2和的结果如何x == y不同?

[Test]
public void StringsAreImmutableObjects()
{
    String str = new String(new char[] {'a', 'l', 'i'});
    String str2 = new String(new char[] {'a', 'l', 'i'});

    Assert.AreEqual("ali", str);
    Assert.AreEqual("ali", str2);

    /*
    * Strange!
    *
    * C# has two "equals" concepts: Equals and ReferenceEquals.
    * For most classes you will encounter, the == operator uses
    * one or the other (or both), and generally only tests for
    * ReferenceEquals when handling reference types (but the
    * string Class is an instance where C# already knows how
    * to test for value equality).
    */

    Assert.AreEqual(str, str2);
    Assert.IsTrue(str == str2);
    Assert.IsTrue(Equals(str, str2));
    Assert.IsFalse(ReferenceEquals(str, str2));

    object x = new StringBuilder("hello").ToString();
    object y = new StringBuilder("hello").ToString();

    Assert.IsTrue(x.Equals(y));
    Assert.IsTrue(object.Equals(x, y));
    Assert.IsFalse(x == y);
    Assert.IsFalse(ReferenceEquals(x, y));
}

以下测试也将通过:

Assert.IsTrue(str is string);
Assert.IsTrue(str2 is string);
Assert.IsTrue(x is string);
Assert.IsTrue(y is string);

标签: c#stringstringbuilder

解决方案


推荐阅读