如何在 Dart 中扩展列表? [英] How do I extend a List in Dart?

查看:51
本文介绍了如何在 Dart 中扩展列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 dart 中创建一个更专业的列表.我不能直接扩展 List.我有哪些选择?

I want to create a more specialized list in dart. I can't directly extend List. What are my options?

推荐答案

dart:collection 中有一个 ListBase 类.如果扩展这个类,只需要实现:

There is a ListBase class in dart:collection. If you extend this class, you only need to implement:

  • 获取长度
  • 设置长度
  • []=
  • []

这是一个例子:

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

这篇关于如何在 Dart 中扩展列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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