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

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

问题描述

让我说:

class Test<T> {
  void method() {
    if (T is int) {
      // T is int
    } 

    if (T == int) {
      // T is int
    }
  }
}

我知道我可以覆盖 == 运算符,但是 == 和<$ c之间的主要区别是什么如果我不重写任何运算符,则Dart中的$ c>是。

I know I can override == operator but what's the main difference between == and is in Dart if I don't override any operator.

编辑:

假设我有

extension MyIterable<T extends num> on Iterable<T> {
  T sum() {
    T total = T is int ? 0 : 0.0; // setting `T == int` works
    for (T item in this) {
      total += item;
    }
    return total;
  }
}

当我使用扩展方法时,例如:

And when I use my extension method with something like:

var addition = MyIterable([1, 2, 3]).sum();

我收到此错误:


类型'double'不是类型'int'

type 'double' is not a subtype of type 'int'


推荐答案


  • same(x,y) 检查 x 是否与 y

    x == y 检查是否 x 应该被认为等于 y 默认实现> operator == identical()相同,但 operator == 进行深度平等检查(或从理论上讲可以是病理性的,可以执行任何操作)。

    x == y checks whether x should be considered equal to y. The default implementation for operator == is the same as identical(), but operator == can be overridden to do deep equality checks (or in theory could be pathological and be implemented to do anything).

    x是T 检查 x 是否具有类型 T x 是一个对象实例

    x is T checks whether x has type T. x is an object instance.

    class MyClass {
      MyClass(this.x);
    
      int x;
    
      @override
      bool operator==(dynamic other) {
        return runtimeType == other.runtimeType && x == other.x;
      }
    
      @override
      int get hashCode => x.hashCode;
    }
    
    void main() {
      var c1 = MyClass(42);
      var c2 = MyClass(42);
      var sameC = c1;
    
      print(identical(c1, c2));    // Prints: false
      print(identical(c1, sameC)); // Prints: true
    
      print(c1 == c2);    // Prints: true
      print(c1 == sameC); // Prints: true
    
      print(c1 is MyClass);      // Prints: true
      print(c1 is c1);           // Illegal.  The right-hand-side must be a type.
      print(MyClass is MyClass); // Prints: false
    }
    

    请注意最后一种情况: MyClass是MyClass false ,因为左侧是 type ,而不是 instance MyClass 。 (但是 MyClass是Type 会是 true 。)

    Note the last case: MyClass is MyClass is false because the left-hand-side is a type, not an instance of MyClass. (MyClass is Type would be true, however.)

    在您的代码中, T是int 是错误的,因为双方都是类型。在这种情况下,您要做 T == int

    In your code, T is int is incorrect because both sides are types. You do want T == int in that case.

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

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