Dart 中的“is"和“=="有什么区别? [英] What is the difference between 'is' and '==' in Dart?
问题描述
假设我有:
class Test<T> {
void method() {
if (T is int) {
// T is int
}
if (T == int) {
// T is int
}
}
}
我知道我可以覆盖 ==
运算符,但是如果我不覆盖,Dart 中 ==
和 is
之间的主要区别是什么任何运营商.
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'
推荐答案
identical(x, y)
检查x
是否与y
是同一个对象.identical(x, y)
checks ifx
is the same object asy
.x == y
检查是否应将x
视为等于y
.默认operator = 的实现=
与identical()
相同,但operator ==
可以被覆盖以进行深度相等检查(或者理论上可能是病态的并被执行以做任何事情).x == y
checks whetherx
should be considered equal toy
. The default implementation foroperator ==
is the same asidentical()
, butoperator ==
can be overridden to do deep equality checks (or in theory could be pathological and be implemented to do anything).x is T
检查x
是否具有T
类型.x
是一个对象实例.x is T
checks whetherx
has typeT
.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 is MyClass
是false
因为左侧是 type,而不是MyClass
的实例.(不过,MyClass is Type
将是true
.)Note the last case:
MyClass is MyClass
isfalse
because the left-hand-side is a type, not an instance ofMyClass
. (MyClass is Type
would betrue
, however.)在您的代码中,
T is int
不正确,因为双方都是类型.在这种情况下,您确实想要T == int
.请注意,T == int
将检查 exact 类型,如果一个类型是另一个的派生类型(例如int == num
将是错误的).In your code,
T is int
is incorrect because both sides are types. You do wantT == int
in that case. Note thatT == int
would check for an exact type and would not be true if one is a derived type of the other (e.g.int == num
would be false).这篇关于Dart 中的“is"和“=="有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!