web-dev-qa-db-fra.com

Comment faire de la classe un IEnumerable en C #?

J'ai donc une classe et une liste générique à l'intérieur, mais elle est privée.

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

Je veux que la classe fonctionne comme ceci:

foreach(Contact in contacts) .... ;

comme ça (ne fonctionne pas):

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

Dans l'exemple ci-dessus, l'instance de classe Contact c doit renvoyer chaque élément des contacts (membre privé de c)

Comment fait-on ça? Je sais que cela doit être IEnumerable avec return return, mais où le déclarer?

19
Ivan Prodanov

Implémentez l'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
}
31
LightStriker

Ou renvoyez un IEnumerator<Contact> en fournissant une méthode GetEnumerator:

class Contacts
{
    List<Contact> contacts;

    public IEnumerator<Contact> GetEnumerator()
    {
        foreach (var contact in contacts)
            yield return contact;
    }
}

foreach recherche GetEnumerator. Jetez un œil ici pour les détails de spécification de langue à ce sujet: https://stackoverflow.com/a/3679993/28424

Comment rendre une classe Visual C # utilisable dans une instruction foreach

13
Tim Schmelter
public class Contacts: IEnumerable
{
     ...... 
    public IEnumerator GetEnumerator()
    {
        return contacts.GetEnumerator();
    }
}

Devrait faire un tour pour vous.

5
Tigran
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; }
}
2
flaugh

Que diriez-vous de simplement étendre List<Contact>

Si vous ne voulez pas étendre une autre classe, c'est une option très simple et rapide:

class Contacts :List<Contact>
{   
}
1
Stephanie