2013-08-27 28 views
1

此问题与Dart语言有关。 我想要一个仅仅是一个List但有一些额外功能的类。在Dart语言中扩展具有额外功能的基类列表类

比如我有一个名为模型类:

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

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

我怎样才能认识到这一点尽可能简单?

P.S.我知道这很简单,但我很不熟悉Object继承,找不到合适的例子。 P.P.S.我也检查了这一点,但不知道它是否过时,并没有理解。

+0

可能的重复[如何在Dart中扩展列表?](http://stackoverflow.com/questions/16247045/how-do-i-extend-a-list-in-dart) –

回答

7

若要使类实现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允许扩展另一个对象)。

+0

谢谢,我是第一个! –

1

你可能会感兴趣quiver.dart的Multimap。它的行为就像一个允许每个键具有多个值的Map。

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

它是在酒吧简单地颤动。我们将很快在某处举办dartdocs。

+0

在我的情况下我需要精确地扩展List类,因为Web UI模板迭代对列表很有用,但对于地图来说有些棘手。 –

+0

Maps和Multimap也有一个'values'属性,您可以迭代,因此'