Is Multiple Iterators is possible in c#?

前端 未结 3 1437
北海茫月
北海茫月 2021-01-15 19:27

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 ma

3条回答
  •  隐瞒了意图╮
    2021-01-15 20:07

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

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

    Is that the kind of thing you were asking?

    You could also potentially write:

    public class Foo : IEnumerable, IEnumerable
    

    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);
            }
        }
    }
    

提交回复
热议问题