在DART中,&;#39;和&;#39;==&;#39;有什么区别? [英] What is the difference between 'is' and '==' in Dart?
本文介绍了在DART中,&;#39;和&;#39;==&;#39;有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有:
class Test<T> {
void method() {
if (T is int) {
// T is int
}
if (T == int) {
// T is int
}
}
}
我知道我可以覆盖==
运算符,但如果我不覆盖任何运算符,==
和is
在DART中的主要区别是什么。
编辑:
假设我有
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;
}
}
当我将我的扩展方法与以下内容一起使用时:
var addition = MyIterable([1, 2, 3]).sum();
我收到此错误:
类型"Double"不是类型"int"的子类型
推荐答案
identical(x, y)
检查x
是否与y
是同一对象。x == y
检查x
是否应被视为等于y
。default implementation foroperator ==
与identical()
相同,但operator ==
可以被重写以执行深度相等性检查(或者在理论上可以是病态的,可以实现为执行任何操作)。x is T
检查x
是否具有T
类型。x
是对象实例。
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
,因为左侧是类型,而不是MyClass
的实例。(但是,MyClass is Type
将是true
。)
在您的代码中,T is int
是不正确的,因为两边都是类型。在这种情况下,您做需要T == int
。请注意,T == int
将检查精确的类型,如果其中一个是另一个的派生类型,则不为真(例如,int == num
将为假)。
这篇关于在DART中,&;#39;和&;#39;==&;#39;有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文