0

在 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?
    }
}
4

1 回答 1

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 中比较Strings 的正确方法实际上是使用string1.equals(string2).

*:重载,而不是覆盖(重要)。请参阅 Jon Skeet 的评论。

于 2012-11-24T07:43:00.627 回答