如何在Dart中比较两个对象以查看它们是否是同一实例? [英] How do I compare two objects to see if they are the same instance, in Dart?

查看:898
本文介绍了如何在Dart中比较两个对象以查看它们是否是同一实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个包含许多实例变量的类。我想重载==运算符(和hashCode),以便可以将实例用作映射中的键。

Say I have a class that has many instance variables,. I want to overload the == operator (and hashCode) so I can use instances as keys in maps.

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 是相同的实例,然后进行计算。

The comparison calculation may be expensive, so I want to check if other is the same instance as this before making that calculation.

怎么做我调用Object类提供的==运算符来执行此操作?

How do I invoke the == operator provided by the Object class to do this ?

推荐答案

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

You're looking for "identical", which will check if 2 instances are the same.

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
}

这篇关于如何在Dart中比较两个对象以查看它们是否是同一实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆