gpt4 book ai didi

dart - 根据另一个变量的类型转换(嵌套列表)对象

转载 作者:行者123 更新时间:2023-12-03 04:58:12 26 4
gpt4 key购买 nike

在我的代码中,我正在创建对象网格。我试图通过抽象化创建网格的循环并从外部传递特定对象来避免重复。例如:

List<List<dynamic>> _createGridWithSameElements({
int height,
int width,
dynamic element,
}){
List<List<dynamic>> vanillaGrid = [];

for (int heightIndex = 0; heightIndex < height; heightIndex++){
List<dynamic> vanillaLine = [];
for (int widthIndex = 0; widthIndex < width; widthIndex++){
vanillaLine.add(element);
}
vanillaGrid.add(vanillaLine);
}

return vanillaGrid;
}

然后,如果我想用字符串创建网格,则可以:

List<List<dynamic>> emptyGrid = _createGridWithSameElements(
height: height,
width: width,
element: Cell.dead()
);

但是,我想基于 element的类型以某种方式重铸网格的各个原子元素。我认为我有两个选择,但我都无法实现:
  • 推断_createGridWithSameElements内部的类型。但是,如果不使用List<List<dynamic>>怎么办呢?
  • _createGridWithSameElements函数调用之后重铸网格。有没有办法做到这一点?
  • 最佳答案

    使用Generics创建可以容纳任何类型的参数。

    也不要忘记传递一个函数来生成其实例,而不是传递元素本身。否则,您将拥有一个包含相同重复实例的网格。

    class Cell{}

    void main(List arguments) {
    final grid = _createGridWithSameElements(
    height: 5,
    width: 10,
    elementGenerator: () => Cell()
    );

    print(grid.runtimeType); // List<List<Cell>>
    }

    List<List<T>> _createGridWithSameElements<T>({
    int height,
    int width,
    T Function() elementGenerator,
    }) {
    final vanillaGrid = <List<T>>[];

    for (int heightIndex = 0; heightIndex < height; heightIndex++) {
    final vanillaLine = <T>[];
    for (int widthIndex = 0; widthIndex < width; widthIndex++) {
    vanillaLine.add(elementGenerator());
    }
    vanillaGrid.add(vanillaLine);
    }

    return vanillaGrid;
    }

    注意一些额外的信息:
  • 函数名称后的<T>告诉Dart将T用作该函数的通用类型。惯例是ETSKV,任何字母或单词都是有效的。
  • 关于dart - 根据另一个变量的类型转换(嵌套列表)对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60190588/

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