扩展列表< T>班级 [英] Extending the List<T> class

查看:49
本文介绍了扩展列表< 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:

  1. 导入'dart:collection';
  2. 扩展ListBase
  3. 实现[]和长度获取器和设置器.

请参见下面的改编的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());
}

这篇关于扩展列表&lt; T&gt;班级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆