假设我有一个包含许多实例变量的类.我想重载==运算符(和hashCode),以便我可以将实例用作映射中的键.
class Foo {
int a;
int b;
SomeClass c;
SomeOtherClass d;
// etc.
bool operator==(Foo other) {
// Long calculation involving a, b, c, d etc.
}
}
Run Code Online (Sandbox Code Playgroud)
比较计算可能很昂贵,所以我想检查是否other与this进行计算前的实例相同.
如何调用Object类提供的==运算符来执行此操作?
Chr*_*man 16
你正在寻找" 相同 ",它将检查2个实例是否相同.
identical(this, other);
Run Code Online (Sandbox Code Playgroud)
更详细的例子?
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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4409 次 |
| 最近记录: |