How to use foreach keyword on custom Objects in C#

后端 未结 3 481
鱼传尺愫
鱼传尺愫 2020-12-14 07:49

Can someone share a simple example of using the foreach keyword with custom objects?

3条回答
  •  忘掉有多难
    2020-12-14 08:23

    Given the tags, I assume you mean in .NET - and I'll choose to talk about C#, as that's what I know about.

    The foreach statement (usually) uses IEnumerable and IEnumerator or their generic cousins. A statement of the form:

    foreach (Foo element in source)
    {
        // Body
    }
    

    where source implements IEnumerable is roughly equivalent to:

    using (IEnumerator iterator = source.GetEnumerator())
    {
        Foo element;
        while (iterator.MoveNext())
        {
            element = iterator.Current;
            // Body
        }
    }
    

    Note that the IEnumerator is disposed at the end, however the statement exits. This is important for iterator blocks.

    To implement IEnumerable or IEnumerator yourself, the easiest way is to use an iterator block. Rather than write all the details here, it's probably best to just refer you to chapter 6 of C# in Depth, which is a free download. The whole of chapter 6 is on iterators. I have another couple of articles on my C# in Depth site, too:

    • Iterators, iterator blocks and data pipelines
    • Iterator block implementation details

    As a quick example though:

    public IEnumerable EvenNumbers0To10()
    {
        for (int i=0; i <= 10; i += 2)
        {
            yield return i;
        }
    }
    
    // Later
    foreach (int x in EvenNumbers0To10())
    {
        Console.WriteLine(x); // 0, 2, 4, 6, 8, 10
    }
    

    To implement IEnumerable for a type, you can do something like:

    public class Foo : IEnumerable
    {
        public IEnumerator GetEnumerator()
        {
            yield return "x";
            yield return "y";
        }
    
        // Explicit interface implementation for nongeneric interface
        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator(); // Just return the generic version
        }
    }
    

提交回复
热议问题