扩展列表< T>班级
问题描述:
是否可以用我自己的特定列表扩展通用列表.像这样:
Is it possible to extend a generic list with my my own specific list. Something like:
class Tweets<Tweet> extends List<T>
如果我想使用自己的构造函数进行构造,构造函数将如何:
And how would a constructor look like, if I wanted to construct with my own constructor:
Datasource datasource = new Datasource('http://search.twitter.com/search.json');
Tweets tweets = new Tweets<Tweet>(datasource);
然后如何调用父构造函数,因为这不是在扩展类中完成的?
And how to call the parent constructor then, as this is not done in a extended class?
答
我发现这是扩展列表行为的原因:
This is what i found out to extend list behavior:
- 导入'dart:collection';
- 扩展ListBase
- 实现[]和长度获取器和设置器.
请参见下面的改编的Tweet示例.它使用自定义的Tweets方法和标准列表方法.
See adapted Tweet example bellow. It uses custom Tweets method and standard list method.
请注意,add/addAll已被删除.
Note that add/addAll has been removed.
输出:
[hello, world, hello]
[hello, hello]
[hello, hello]
代码:
import 'dart:collection';
class Tweet {
String message;
Tweet(this.message);
String toString() => message;
}
class Tweets<Tweet> extends ListBase<Tweet> {
List<Tweet> _list;
Tweets() : _list = new List();
void set length(int l) {
this._list.length=l;
}
int get length => _list.length;
Tweet operator [](int index) => _list[index];
void operator []=(int index, Tweet value) {
_list[index]=value;
}
Iterable<Tweet> myFilter(text) => _list.where( (Tweet e) => e.message.contains(text));
}
main() {
var t = new Tweet('hello');
var t2 = new Tweet('world');
var tl = new Tweets();
tl.addAll([t, t2]);
tl.add(t);
print(tl);
print(tl.myFilter('hello').toList());
print(tl.where( (Tweet e) => e.message.contains('hello')).toList());
}