gpt4 book ai didi

class - 使用Dart语言扩展具有附加功能的基本List类

转载 作者:行者123 更新时间:2023-12-03 03:07:36 24 4
gpt4 key购买 nike

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

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

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

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

我如何才能尽可能轻松地实现这一目标?

附言我知道这很简单,但是我对Object继承不甚了解,并且找不到合适的示例。
P.P.S.我也检查了一下,但不知道它是否已过时,也没听懂。

最佳答案

要使一个类实现List,有几种方法:

  • 扩展ListBase并实现 length operator[] 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并实现 length operator[] 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
    }
  • List 中使用quiver package委派给另一个DelegatingList:

  • import 'package:quiver/collection.dart';

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

    List<E> get delegate => _l;

    // your custom methods
    }

    根据您的代码,每个选项都有其优势。如果包装/删除现有列表,则应使用最后一个选项。否则,请根据您的类型层次结构使用两个前两个选项之一(mixin允许扩展另一个Object)。

    关于class - 使用Dart语言扩展具有附加功能的基本List类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18459181/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com