【问题标题】:How do I compare two objects to see if they are the same instance, in Dart?如何在 Dart 中比较两个对象以查看它们是否是同一个实例?
【发布时间】:2013-08-25 11:59:31
【问题描述】:

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

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 类提供的 == 运算符来执行此操作?

【问题讨论】:

    标签: dart


    【解决方案1】:

    您正在寻找“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
    }
    

    【讨论】:

    • 如果您覆盖operator ==,您还需要覆盖hashCode。请参阅此答案here 了解如何执行此操作
    • 如果我想检查一个模型列表是否已经包含一个特定的对象?
    【解决方案2】:

    您可以使用identical(this, other)

    【讨论】:

      【解决方案3】:

      为了完整起见,这是对现有答案的补充答案。

      如果某个类Foo覆盖==,那么默认实现是返回它们是否是同一个对象。 documentation 声明:

      所有对象的默认行为是当且仅当这个对象和其他对象是同一个对象时才返回true。

      【讨论】:

        【解决方案4】:

        在一个不同但相似的注释中,在框架调用检查对象之间的相等性的情况下,例如如果list.toSet() 从列表中获取唯一元素,identical(this, other) 可能不是一个选择。那个时候类必须重写== operatorhasCode() 方法。

        但是对于这种情况,另一种方法是使用equatable 包。这节省了很多样板代码,当你有很多模型类时特别方便。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-01-31
          • 1970-01-01
          • 1970-01-01
          • 2018-05-14
          • 1970-01-01
          • 1970-01-01
          • 2014-03-22
          相关资源
          最近更新 更多