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

初学Dart:==与identical()的区别及差异原因咨询

Dart中==运算符与identical()函数的区别解析

核心定义差异

  • identical(obj1, obj2):严格校验两个引用是否指向内存中的同一个对象实例,等价于Python里的is运算符。无论对象内容如何,只要是同一实例就返回true。
  • ==运算符:默认继承自Object类的实现,此时和identical()效果完全一致;但如果类重写了==方法,就会按照自定义逻辑判断值相等,而非实例是否相同。

结合你的代码示例分析

你的Dart代码中:

void main() {
  var a = [1, 2, 3];
  var b = a;
  var c = [1, 2, 3];

  print(identical(a, b)); // true(a和b指向同一列表实例)
  print(identical(a, c)); // false(a和c是两个独立的列表实例)
  print(a == c);  // false(Dart的List默认未重写==,仍按实例判断)
}

这和Python的差异源于:Python的list类已经内置重写了==方法,会遍历判断所有元素是否相等;而Dart的List默认没有做这个实现,所以==仍沿用Object的实例判断逻辑。如果需要在Dart中判断列表内容相等,可以使用collection包中的ListEquality工具,或者自行实现元素比较逻辑。

基础数据类型的表现

对于int、String、bool这类基础类型,由于Dart的字符串驻留和数值常量池优化,==和identical()往往结果一致:

void main() {
  int x = 10;
  int y = 10;
  print(identical(x, y)); // true
  print(x == y); // true

  String s1 = "hello";
  String s2 = "hello";
  print(identical(s1, s2)); // true
  print(s1 == s2); // true
}

但要注意,这种一致是优化带来的特例,而非两者本质相同。比如动态拼接的字符串:

String s3 = "hel" + "lo";
String s4 = "hello";
print(identical(s3, s4)); // 结果取决于编译器优化,不一定为true
print(s3 == s4); // 一定为true,因为String类重写了==判断内容相等

自定义类的场景

自定义类默认情况下,==和identical()效果一致,因为没有重写==方法:

class Person {
  String name;
  Person(this.name);
}

void main() {
  Person p1 = Person("Alice");
  Person p2 = Person("Alice");
  print(identical(p1, p2)); // false
  print(p1 == p2); // false
}

如果需要让==判断值相等,必须重写==和hashCode方法(两者需配套实现):

class Person {
  String name;
  Person(this.name);

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is Person &&
          runtimeType == other.runtimeType &&
          name == other.name;

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

void main() {
  Person p1 = Person("Alice");
  Person p2 = Person("Alice");
  print(identical(p1, p2)); // false(不同实例)
  print(p1 == p2); // true(值相等)
}

总结

  • 要判断两个对象是否为同一实例:用identical();
  • 要判断两个对象的值是否相等:用==,但需确认当前类是否重写了==方法;
  • Dart内置集合(List、Map等)默认未重写==,如需值比较需额外处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 15:22:43