Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/dart/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么@override of";获得;在这里(Dart中的语法)_Dart - Fatal编程技术网

为什么@override of";获得;在这里(Dart中的语法)

为什么@override of";获得;在这里(Dart中的语法),dart,Dart,在官方的颤振示例中,有一个类,它不扩展另一个类。那么为什么int-get-hashCode会覆盖它呢?也就是说,没有什么可以覆盖的,不是吗 class Item { final int id; final String name; final Color color; final int price = 42; Item(this.id, this.name) // To make the sample app look nicer, each item is

在官方的颤振示例中,有一个类,它不扩展另一个类。那么为什么
int-get-hashCode
会覆盖它呢?也就是说,没有什么可以覆盖的,不是吗

class Item {
  final int id;
  final String name;
  final Color color;
  final int price = 42;

  Item(this.id, this.name)
      // To make the sample app look nicer, each item is given one of the
      // Material Design primary colors.
      : color = Colors.primaries[id % Colors.primaries.length];

  @override
  int get hashCode => id;

  @override
  bool operator ==(Object other) => other is Item && other.id == id;
}
发件人:

所有对象都有哈希代码。默认哈希代码仅表示对象的标识,这与默认运算符==实现仅在对象相同时才考虑对象相等的方式相同(请参见identityHashCode)

来自

因为对象是Dart类层次结构的根,所以其他每个Dart类都是对象的子类

每个类都是
对象类的子类
,因此它们始终具有相同的属性,这就是您要覆盖的内容

现在,如果您询问为什么要同时覆盖
hashCode
equals
,请查看官方的

哈希代码是单个整数,表示影响运算符==比较的对象状态。所有对象都有哈希代码。默认哈希代码仅表示对象的标识,这与默认运算符==实现仅在对象相同时才考虑对象相等的方式相同(请参见identityHashCode)

换句话说,每次创建类Item的对象时,都会为其生成hashCode属性

现在,如果您想检查类item的两个对象的相等性,Dart(如Java)将通过执行hashcode的
==
来检查相等性

这意味着
Item object1!=Item Object2
,因为每个对象都有自己独特的哈希代码

因此,hashcode必须被覆盖,在这种情况下,可以检查
Item object1
是否与
Item object2