在C#中可以使用多个迭代器吗? [英] Is Multiple Iterators is possible in c#?

查看:179
本文介绍了在C#中可以使用多个迭代器吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在c#.net中可以有多个迭代器(对于单个类或对象)吗?如果是,请给我一些简单的例子。抱歉,如果这个问题无法理解,请告诉我。

Can multiple iterators (for a single class or object) is possible in c#.net? If it is give me some simple examples. Sorry if the question is not understandable and please make me clear.

推荐答案

您当然可以创建不同的迭代器以不同的方式遍历。例如,您可以拥有:

You could certainly create different iterators to traverse in different ways. For example, you could have:

public class Tree<T>
{
    public IEnumerable<T> IterateDepthFirst()
    {
        // Iterate, using yield return
        ...
    }

    public IEnumerable<T> IterateBreadthFirst()
    {
        // Iterate, using yield return
        ...
    }
}

您问的是这种事情吗?

您还可以可能会写:

public class Foo : IEnumerable<int>, IEnumerable<string>

但这会引起很多混乱,并且 foreach 循环将选择具有未明确实现的 GetEnumerator 调用的任何一个。

but that would cause a lot of confusion, and the foreach loop would pick whichever one had the non-explicitly-implemented GetEnumerator call.

您可以同时在同一集合上重复多次:

You can also iterate multiple times over the same collection at the same time:

foreach (Person person1 in party)
{
    foreach (Person person2 in party)
    {
        if (person1 != person2)
        {
            person1.SayHello(person2);
        }
    }
}

这篇关于在C#中可以使用多个迭代器吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆