You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Dart中为Body类重写相等运算符,是否需重写Arm与Leg类的?

问题解答

是的,必须为Arm和Leg类重写相等运算符(==)以及hashCode方法,否则Body类的相等判断逻辑会不符合预期。

原因说明

Dart中所有类默认继承自Object,而Object的==运算符默认比较对象的引用地址——也就是说,只有当两个变量指向内存中的同一个实例时,==才会返回true。

如果不为Arm和Leg重写==,那么即使两个Arm实例的内部状态完全一致,在Body的==判断中执行other._arm == _arm时,会因为它们是不同实例而返回false,导致两个属性完全一致的Body实例被判定为不相等,这通常不符合业务场景中“内容相等即对象相等”的需求。

示例代码

正确的做法是为所有关联类都实现==和hashCode:

  1. 为Leg和Arm实现相等逻辑:
class Leg {
  // 假设Leg有属性,比如长度
  final double length;

  Leg(this.length);

  @override
  bool operator ==(Object other) {
    if (identical(this, other)) return true;
    return other is Leg && other.length == length;
  }

  @override
  int get hashCode => length.hashCode;
}

class Arm {
  // 假设Arm有属性,比如力量值
  final int strength;

  Arm(this.strength);

  @override
  bool operator ==(Object other) {
    if (identical(this, other)) return true;
    return other is Arm && other.strength == strength;
  }

  @override
  int get hashCode => strength.hashCode;
}
  1. 再实现Body的相等逻辑:
class Body {
  Leg _leg;
  Arm _arm;

  Body(this._leg, this._arm);

  @override
  bool operator ==(Object other) {
    if (identical(this, other)) return true;
    return other is Body && other._leg == _leg && other._arm == _arm;
  }

  @override
  int get hashCode => Object.hash(_leg, _arm);
}

额外注意

重写==时必须同步重写hashCode,因为Dart的集合(如HashSet、HashMap)依赖hashCode来管理元素,两个相等的对象必须拥有相同的hashCode,否则会导致集合行为异常。

内容的提问来源于stack exchange,提问作者Davout

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 10:25:07