在面向对象语言(如C#)中,CLR如何区分具有相同值的相同类型的对象?
例如:
class Foo
{
public string name {get; set;}
public foo(string name)
{
this.Name = name;
}
}
class Bar
{
public void Main()
{
Foo foo1 = new Foo("Jim"); //This foo is named "Jim."
Foo foo2 = new Foo("Jim"); //So is this one.
bool areEqual = (foo1 == foo2); //How is the CLR determining equivalence?
}
}
答案 0 :(得分:3)
在许多OO语言中(包括C#,虽然行为可以重载*),==
运算符检查对每个对象的引用是否相等,而不是对象的内容。
因此,例如,发生了这样的事情:
Foo foo1 = new Foo("Jim");
// The Foo pointed to by foo1 is stored at memory location 0x47008
Foo foo2 = new Foo("Jim");
// The Foo pointed to by foo2 is stored at memory location 0x57008
bool areEqual = (foo1 == foo2);
// areEqual is false, as the comparison being made is 0x47008 == 0x57008
除非明确重载,否则这是C#中所有对象的行为。一个值得注意的例外是string
类型,它已经重载* ==
来实际比较字符串的内容。反例是Java,不允许运算符重载;在Java中比较String
的正确方法实际上是使用string1.equals(string2)
。
*:重载,而不是重写(重要)。请参阅Jon Skeet的评论。