如何扩展在DART一个列表?如何扩展在DART一个列表?(How do I extend a Lis

2019-05-12 01:57发布

我想创建镖更专业的列表。 我不能直接扩展列表 。 我有哪些选择?

Answer 1:

若要使类实现列表有几种方法:

  • 延伸ListBase和执行lengthoperator[] operator[]=length=
import 'dart:collection';

class MyCustomList<E> extends ListBase<E> {
  final List<E> l = [];
  MyCustomList();

  void set length(int newLength) { l.length = newLength; }
  int get length => l.length;
  E operator [](int index) => l[index];
  void operator []=(int index, E value) { l[index] = value; }

  // your custom methods
}
  • 密新ListMixin和执行lengthoperator[] operator[]=length=
import 'dart:collection';

class MyCustomList<E> extends Base with ListMixin<E> {
  final List<E> l = [];
  MyCustomList();

  void set length(int newLength) { l.length = newLength; }
  int get length => l.length;
  E operator [](int index) => l[index];
  void operator []=(int index, E value) { l[index] = value; }

  // your custom methods
}
  • 委派到其他ListDelegatingList从箭袋包 :
import 'package:quiver/collection.dart';

class MyCustomList<E> extends DelegatingList<E> {
  final List<E> _l = [];

  List<E> get delegate => _l;

  // your custom methods
}
  • 委派到其他ListDelegatingList从收集包 :
import 'package:collection/wrappers.dart';

class MyCustomList<E> extends DelegatingList<E> {
  final List<E> _l;

  MyCustomList() : this._(<E>[]);
  MyCustomList._(l) :
    _l = l,
    super(l);

  // your custom methods
}

根据您的代码,每一个选项都有各自的优点。 如果你包/委派你应该使用的最后一个选项现有列表。 否则,使用取决于你的类型层次结构中的两个第一选项之一(MIXIN允许扩展的其他对象)。



Answer 2:

有一个在镖ListBase类:集合。 如果你扩展这个类,你只需要实现:

  • get length
  • set length
  • []=
  • []

下面是一个例子:

import 'dart:collection';

class FancyList<E> extends ListBase<E> {
  List innerList = new List();

  int get length => innerList.length;

  void set length(int length) {
    innerList.length = length;
  }

  void operator[]=(int index, E value) {
    innerList[index] = value;
  }

  E operator [](int index) => innerList[index];

  // Though not strictly necessary, for performance reasons
  // you should implement add and addAll.

  void add(E value) => innerList.add(value);

  void addAll(Iterable<E> all) => innerList.addAll(all);
}

void main() {
  var list = new FancyList();

  list.addAll([1,2,3]);

  print(list.length);
}


文章来源: How do I extend a List in Dart?
标签: dart