假设我有:
class Test<T> {
void method() {
if (T is int) {
// T is int
}
if (T == int) {
// T is int
}
}
}
Run Code Online (Sandbox Code Playgroud)
我知道我可以覆盖==运算符,但是如果我不覆盖任何运算符,Dart==和isDart之间的主要区别是什么。
编辑:
说我有
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;
}
}
Run Code Online (Sandbox Code Playgroud)
当我使用我的扩展方法时:
var addition = MyIterable([1, 2, 3]).sum();
Run Code Online (Sandbox Code Playgroud)
我收到此错误:
“double”类型不是“int”类型的子类型
identical(x, y)检查是否x与y.
x == y检查是否x应被视为等于y。for的默认实现operator ==与 相同identical(),但operator ==可以被覆盖以进行深度相等性检查(或者理论上可能是病态的并且可以执行任何操作)。
x is T检查是否x有 type 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
}
Run Code Online (Sandbox Code Playgroud)
注意最后一种情况:MyClass is MyClass是false因为左手侧是一个类型,而不是一个实例的MyClass。(MyClass is Type会true然而,。)
在您的代码中,T is int不正确,因为双方都是类型。在那种情况下你确实想要T == int。请注意,T == int将检查一个确切的类型,如果一个是另一个的派生类型,则它不会为真(例如int == num,为假)。
| 归档时间: |
|
| 查看次数: |
278 次 |
| 最近记录: |