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

2019-04-03 23:19发布

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

class Contacts
{
    List<Contact> contacts;
    ...
}

I want to make the class work as this would do:

foreach(Contact in contacts) .... ;

like this (not working):

Contacts c;
foreach(Contact in c) .... ;

In the example above the Contact class instance c has to yield return every item from contacts(private member of c)

How do I do it? I know it has to be IEnumerable with yield return, but where to declare that?

5条回答
Root(大扎)
2楼-- · 2019-04-03 23:37

Or return an IEnumerator<Contact> by providing a GetEnumerator method:

class Contacts
{
    List<Contact> contacts;

    public IEnumerator<Contact> 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

查看更多
该账号已被封号
3楼-- · 2019-04-03 23:39
class Program
{
    static void Main(string[] args)
    {
        var list = new Contacts();
        var a = new Contact() { Name = "a" };
        var b = new Contact() { Name = "b" };
        var c = new Contact() { Name = "c" };
        var d = new Contact() { Name = "d" };
        list.ContactList = new List<Contact>();
        list.ContactList.Add(a);
        list.ContactList.Add(b);
        list.ContactList.Add(c);
        list.ContactList.Add(d);

        foreach (var i in list)
        {
            Console.WriteLine(i.Name);
        }
    }
}

class Contacts : IEnumerable<Contact>
{
    public List<Contact> ContactList { get; set; }

    public IEnumerator<Contact> GetEnumerator()
    {
        return ContactList.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return ContactList.GetEnumerator();
    }
}

class Contact
{
    public string Name { get; set; }
}
查看更多
萌系小妹纸
4楼-- · 2019-04-03 23:40

How about just extending List<Contact>

If you don't want to extend any other class its a very simple, fast option:

class Contacts :List<Contact>
{   
}
查看更多
劳资没心,怎么记你
5楼-- · 2019-04-04 00:01

Implement the interface IEnumerable:

class Contacts : IEnumerable<Contact>
{
    List<Contact> contacts;

    #region Implementation of IEnumerable
    public IEnumerator<Contact> GetEnumerator()
    {
        return contacts.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
    #endregion
}
查看更多
Emotional °昔
6楼-- · 2019-04-04 00:02
public class Contacts: IEnumerable
{
     ...... 
    public IEnumerator GetEnumerator()
    {
        return contacts.GetEnumerator();
    }
}

Should do a trick for you.

查看更多
登录 后发表回答