我有一个抽象类Filter,它由各种事务过滤器(例如DateFilter、AccountFilter等)实现。
abstract class TransactionFilter {
String asString();
bool operator >(TransactionFilter other);
}
// Concrete implementations
class DateFilter implements TransactionFilter {
DateTime startDate, endDate;
DateFilter(this.startDate, this.endDate);
// ⏹ ERROR
// 'DateFilter.>' ('bool Function(DateFilter)') isn't a valid override of
// 'TransactionFilter.>' ('bool Function(TransactionFilter)')
bool operator >(DateFilter other) =>
startDate.isBefore(other.startDate) && endDate.isAfter(other.endDate);
}
class AccountFilter implements TransactionFilter {
List<int> accounts;
DateFilter(this.accounts);
// Same error as above
bool operator >(AccountFilter other) =>
other.any((e) => !accounts.contains(e))
}这似乎是因为Dart不认为DateFilter和AccountFilter等同于TransactionFilter。
编辑:我希望>操作符被同一子类型的类严格使用(例如,比较两个DateFilter实例)。在给定的示例中,我如何做到这一点?
发布于 2020-07-05 17:06:59
你正在做的事情并没有使类型安全的意义。您的TransactionFilter指定从TransactionFilter继承的所有类都有一个>运算符,该运算符可以与TransactionFilter类型的任何对象进行比较。
因此,当您在子类中将运算符定义为:
bool operator >(DateFilter other)或者:
bool operator >(AccountFilter other)这是不允许的,因为DateFilter和AccountFilter比TransactionFilter限制性更强(您的DateFilter类只允许与其他DateFilter进行比较,而不允许与AccountFilter进行比较)。
下面是一个示例,说明如何使用更新来代替泛型:
abstract class TransactionFilter<T extends TransactionFilter<T>> {
String asString();
bool operator >(T other);
}
// Concrete implementations
class DateFilter implements TransactionFilter<DateFilter> {
DateTime startDate, endDate;
DateFilter(this.startDate, this.endDate);
bool operator >(DateFilter other) =>
startDate.isBefore(other.startDate) && endDate.isAfter(other.endDate);
@override
String asString() {
// TODO: implement asString
throw UnimplementedError();
}
}
class AccountFilter implements TransactionFilter<AccountFilter> {
List<int> accounts;
AccountFilter(this.accounts);
bool operator >(AccountFilter other) =>
other.accounts.any((e) => !accounts.contains(e));
@override
String asString() {
// TODO: implement asString
throw UnimplementedError();
}
}https://stackoverflow.com/questions/62741036
复制相似问题