Extending the List<T> class [duplicate]

隐身守侯 提交于 2021-02-07 13:38:54

问题


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?


回答1:


This is what i found out to extend list behavior:

  1. import 'dart:collection';
  2. extends ListBase
  3. implement [] and length getter and setter.

See adapted Tweet example bellow. It uses custom Tweets method and standard list method.

Note that add/addAll has been removed.

Output:

[hello, world, hello]
[hello, hello]
[hello, hello]

Code:

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());
}



回答2:


Dart's List is an abstract class with factories.

I think you could implement it like this:

class Tweet {
  String message;

  Tweet(this.message);
}

class Tweets<Tweet> implements List<Tweet> {
  List<Tweet> _list;

  Tweets() : _list = new List<Tweet>();

  add(Tweet t) => _list.add(t);
  addAll(Collection<Tweet> tweets) => _list.addAll(tweets);
  String toString() => _list.toString();
}


main() {
  var t = new Tweet('hey');
  var t2 = new Tweet('hey');

  var tl = new Tweets();
  tl.addAll([t, t2]);

  print(tl);
}

There doesn't seem to be any direct way to do this and looks like there's also a bug ticket: http://code.google.com/p/dart/issues/detail?id=2600

Update: One way is to use noSuchMethod() and forward calls.



来源:https://stackoverflow.com/questions/13857151/extending-the-listt-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!