gpt4 book ai didi

dart - Dart库之旅中的迭代示例错误

转载 作者:行者123 更新时间:2023-12-03 03:42:37 25 4
gpt4 key购买 nike

问题

如何实现“Dart库之旅”中的迭代示例?

我知道这是必须补充的代码,但是我该如何补充呢?

A Tour of the Dart Libraries

class Process {
// Represents a process...
}

class ProcessIterator implements Iterator<Process> {
@override
Process get current => ...
@override
bool moveNext() => ...
}

// A mythical class that lets you iterate through all
// processes. Extends a subclass of [Iterable].
class Processes extends IterableBase<Process> {
@override
final Iterator<Process> iterator = ProcessIterator();
}

void main() {
// Iterable objects can be used with for-in.
for (var process in Processes()) {
// Do something with the process.
}
}

开发环境
  • Dart 2
  • DartPad

  • 尝试→错误

    我自己阅读并执行了文档,但是发生以下错误。
    class ProcessIterator implements Iterator<Process> {
    @override
    Process get current => new Process();
    @override
    bool moveNext() => false;
    }

    ->错误:“IterableBase”需要0个类型参数。

    最好的祝福,

    最佳答案

    两件事情。

    1)Process在网络上不可用,因此您的DartPad示例不起作用。

    2)IterableBasedart:collection中。不要忘记导入。

    这段代码似乎适合我:

    import 'dart:collection';

    class ProcessIterator implements Iterator<int> {
    @override
    int get current => 0;
    @override
    bool moveNext() => false;
    }

    // A mythical class that lets you iterate through all
    // processes. Extends a subclass of [Iterable].
    class Processes extends IterableBase<int> {
    @override
    final Iterator<int> iterator = ProcessIterator();
    }

    main() {
    for (var thing in Processes()) {
    print(thing);
    }
    }

    请记住,将 sync*用于自定义迭代器通常要容易得多。
    Iterable<int> _myProcesses() sync* {
    yield 1;
    yield 2;
    yield 3;
    }

    main() {
    for (var thing in _myProcesses()) {
    print(thing);
    }
    }

    关于dart - Dart库之旅中的迭代示例错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51666644/

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