How to make the class as an IEnumerable in C#?

前端 未结 5 1526
长情又很酷
长情又很酷 2020-12-31 01:07

So I\'ve got a class and a generic List inside of it, but it is private.

class Contacts
{
    List contacts;
    ...
}

I wan

5条回答
  •  心在旅途
    2020-12-31 02:00

    Or return an IEnumerator by providing a GetEnumerator method:

    class Contacts
    {
        List contacts;
    
        public IEnumerator GetEnumerator()
        {
            foreach (var contact in contacts)
                yield return contact;
        }
    }
    

    The foreach looks for GetEnumerator. Have a look here for the language specification details regarding this: https://stackoverflow.com/a/3679993/284240

    How to make a Visual C# class usable in a foreach statement

提交回复
热议问题