在以下测试中: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);