Dart中==和===有什么区别? [英] What is the difference between == and === in Dart?

查看:85
本文介绍了Dart中==和===有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Dart支持==和===吗?平等与身份之间有什么区别?

Does Dart support == and === ? What is the difference between equality and identity?

推荐答案

Dart支持 == 来实现相等性,而 identical(a,b)来实现身份性.Dart不再支持 === 语法.

Dart supports == for equality and identical(a, b) for identity. Dart no longer supports the === syntax.

当您要检查对象是否也相等"时,请使用 == 进行相等.您可以在类中实现 == 方法来定义相等性的含义.例如:

Use == for equality when you want to check if too objects are "equal". You can implement the == method in your class to define what equality means. For example:

class Person {
  String ssn;
  String name;

  Person(this.ssn, this.name);

  // Define that two persons are equal if their SSNs are equal
  bool operator ==(other) {
    return (other is Person && other.ssn == ssn);
  }
}

main() {
  var bob =  Person('111', 'Bob');
  var robert =  Person('111', 'Robert');

  print(bob == robert); // true

  print(identical(bob, robert)); // false, because these are two different instances
}

请注意, a == b 的语义是:

  • 如果 a b null ,则返回 identical(a,b)
  • 否则,返回 a.==(b)
  • If either a or b are null, return identical(a, b)
  • Otherwise, return a.==(b)

使用 identical(a,b)检查两个变量是否引用同一实例.相同是在 dart中找到的顶级功能:core .

Use identical(a, b) to check if two variables reference the same instance. identical is a top-level function found in dart:core.

这篇关于Dart中==和===有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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