我正在开发一个测量类,因此我想提供一个很好的 API 来比较两个测量值。
为了处理集合中的排序,我实现了Comparator. 对于一个很好的 API,我还实现了比较运算符<, <=, =>, >, ==。
所以我的类有以下方法:
bool operator <=(SELF other) => _value <= other._value;
bool operator <(SELF other) => _value < other._value;
bool operator >(SELF other) => _value > other._value;
bool operator >=(SELF other) => _value >= other._value;
@override
bool operator ==(Object other) =>
identical(this, other) || other is UnitValue && runtimeType == other.runtimeType && _value == other._value;
@override
int get hashCode => _value.hashCode;
int compareTo(SELF other) => _value.compareTo(other._value);
Run Code Online (Sandbox Code Playgroud)
感觉我不得不添加太多的样板代码。Dart 是否提供任何混合来基于运算符子集获得所有实现?
我不这么认为......但是您可以使用一个简单的 mixin 来基于Comparable实现来实现运算符:
mixin Compare<T> on Comparable<T> {
bool operator <=(T other) => this.compareTo(other) <= 0;
bool operator >=(T other) => this.compareTo(other) >= 0;
bool operator <(T other) => this.compareTo(other) < 0;
bool operator >(T other) => this.compareTo(other) > 0;
bool operator ==(other) => other is T && this.compareTo(other) == 0;
}
Run Code Online (Sandbox Code Playgroud)
用法示例:
class Vec with Comparable<Vec>, Compare<Vec> {
final double x;
final double y;
Vec(this.x, this.y);
@override
int compareTo(Vec other) =>
(x.abs() + y.abs()).compareTo(other.x.abs() + other.y.abs());
}
main() {
print(Vec(1, 1) > Vec(0, 0));
print(Vec(1, 0) > Vec(0, 0));
print(Vec(0, 0) == Vec(0, 0));
print(Vec(1, 1) <= Vec(2, 0));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3725 次 |
| 最近记录: |