1

这个问题是关于 Dart 语言的。我想要一个只是一个列表但具有一些额外功能的类。

例如,我有一个名为 Model 的类:

class Model{
  String name;
  int type;
  Model(this.name, this.type);
}

我知道模型的类型只能取四个值:从 0 到 3。我想要一个方法,它可以给我一个指定类型的模型列表,例如List<Model> modelCollection.getByType(int type);. 我计划在该类中有四个“隐藏”模型列表(按类型分组)。因此,我需要覆盖 List 元素的添加和删除,以使隐藏列表保持最新。

我怎样才能尽可能容易地意识到这一点?

PS我知道这很简单,但是我对对象继承不太熟悉,找不到合适的例子。PPS 我也检查过这个但不知道它是否过时并且没有抓住这个想法。

4

3 回答 3

9

让一个类实现List有几种方法:

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
}
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
}
import 'package:quiver/collection.dart';

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

  List<E> get delegate => _l;

  // your custom methods
}

根据您的代码,这些选项中的每一个都有其优势。如果您包装/委托现有列表,则应使用最后一个选项。否则,根据您的类型层次结构使用前两个选项之一(mixin 允许扩展其他对象)。

于 2013-08-29T08:19:37.663 回答
2

一种基本方法是使用IterableMixin扩展 Object 。似乎您甚至不需要覆盖“长度”吸气剂,或者说 IterableMixin 已经提供的所有方法。

import 'dart:collection';    

class Model {
   String name;
   int type;

   Model(this.name, this.type) {
   }
}

class ModelCollection extends Object with IterableMixin {

   List<Model> _models;
   Iterator get iterator => _models.iterator;

   ModelCollection() {
      this._models = new List<Model>();
   }

   //get one or the first type
   Model elementByType(int type) {

     for (Model model in _models) {
       if (model.type == type) {
          return model;
       }
     }       
   }

   //get all of the same type
   List<Model> elementsByType(int type) {

      List<Model> newModel = new List<Model>();

      for (Model model in _models) {
         if (model.type == type) {
            newModel.add(model);
         }
      }
      return newModel;       
   }

   add(Model model) {
      this._models.add(model);
   }
}

请原谅我的强静态类型。

于 2013-08-29T08:43:21.277 回答
1

您可能对 quiver.dart 的 Multimap 感兴趣。它的行为类似于允许每个键有多个值的 Map。

这是 github 上的代码:https ://github.com/google/quiver-dart/blob/master/lib/src/collection/multimap.dart#L20

它在酒吧就像颤抖一样。我们很快就会在某个地方托管 dartdocs。

于 2013-08-27T07:26:01.557 回答