2013-08-25 36 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

啊,是的,謝謝。五分鐘更多的研究會告訴我這一點! –

相關問題