2013-08-25 38 views
4

说我有一个有很多实例变量的类。我想重载==操作符(和hashCode),所以我可以在地图中使用实例作为键。如何在Dart中比较两个对象以查看它们是否是相同的实例?

class Foo { 
    int a; 
    int b; 
    SomeClass c; 
    SomeOtherClass d; 
    // etc. 

    bool operator==(Foo other) { 
    // Long calculation involving a, b, c, d etc. 
    } 
} 

比较计算可能是昂贵的,所以我要检查,如果other是同一个实例this使得该计算之前。

如何调用Object类提供的==操作符来执行此操作?

回答

8

您正在寻找“identical”,它将检查2个实例是否相同。

identical(this, other); 

一个更详细的例子?

class Person { 
    String ssn; 
    String name; 

    Person(this.ssn, this.name); 

    // Define that two persons are equal if their SSNs are equal 
    bool operator ==(Person other) { 
    return (other.ssn == ssn); 
    } 
} 

main() { 
    var bob = new Person('111', 'Bob'); 
    var robert = new Person('111', 'Robert'); 

    print(bob == robert); // true 

    print(identical(bob, robert)); // false, because these are two different instances 
} 
+0

啊,是的,谢谢。五分钟更多的研究会告诉我这一点! –

相关问题