dart 是否支持运算符重载 [英] Does dart support operator overloading
本文介绍了dart 是否支持运算符重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我读到 Dart 不支持函数重载.它是否支持运算符重载?如果是,你能在一个简单的例子中告诉我它是如何完成的吗?以及有哪些优势等?
I read that Dart does not support function overloading. Does it support operator overloading? If yes, can you show me how it's done in a simple example? And what are some advantages etc?
推荐答案
在新版本中使用 ==
运算符尝试重载时,所选答案不再有效.现在你需要这样做:
The chosen answer is no longer valid when you try overloads using the ==
operator in the new version. Now you need to do this:
class MyClass {
@override
bool operator ==(other) {
// compare this to other
}
}
但这并不安全.other
未指定为类型,可能会发生意外.例如:
But it's not safe. other
is not specified as a type, Something unexpected may happened. For example:
void main() {
var a = A(1);
var b = B(1);
var result = a == b;
print(result); //result is true
}
class A {
A(this.index);
final int index;
@override
bool operator ==(other) => other.index == index;
}
class B {
B(this.index);
final int index;
}
所以你可以这样做:
class A {
A(this.index);
final int index;
@override
bool operator ==(covariant A other) => other.index == index;
}
你需要使用covariant
.因为 Object 重载了 ==
运算符.
You need to use covariant
. Because Object overloads the ==
operator.
测试对象类型:
访问:hash_and_equals
class A {
A(this.index);
final int index;
@override
bool operator ==(other) => other is A && (other.index == index);
@override
int get hashCode => index;
}
这篇关于dart 是否支持运算符重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文