问题描述
让我说:
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();
我收到此错误:
推荐答案
-
检查
x
是否与y $ c $是同一对象c>。
x == y
检查是否x
应该被认为等于y
。 默认实现> operator == 与identical()
相同,但operator == $ c可以重写$ c>进行深度平等检查(或从理论上讲可以是病理性的,可以执行任何操作)。
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是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是MyClass
是false
,因为左侧是 type ,而不是 instance 为MyClass
。 (但是MyClass是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是int
是错误的,因为双方都是类型。在这种情况下,您要做要T == int
。In your code,
T is int
is incorrect because both sides are types. You do wantT == int
in that case.这篇关于Dart中“ is”和“ ==”有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!