string x = "hello";
string y = String.Copy(x);
string z = "hello";
To test if x
points to the same object as y
:
(object)x == (object)y // false
x.ReferenceEquals(y) // false
x.ReferenceEquals(z) // true (because x and z are both constants they
// will point to the same location in memory)
To test if x
has the same string value as y
:
x == y // true
x == z // true
x.Equals(y) // true
y == "hello" // true
Note that this is different to Java.
In Java the ==
operator is not overloaded so a common mistake in Java is:
y == "hello" // false (y is not the same object as "hello")
For string comparison in Java you need to always use .equals()
y.equals("hello") // true
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…