Подтвердить что ты не робот

Как сделать класс IEnumerable в С#?

Итак, у меня есть класс и общий список внутри него, но он закрыт.

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

Я хочу, чтобы класс работал так:

foreach(Contact in contacts) .... ;

как это (не работает):

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

В приведенном выше примере экземпляр класса Contact c должен возвращать каждый элемент из контактов (частный член c)

Как мне это сделать? Я знаю, что это должно быть IEnumerable с возвратом доходности, но где объявить это?

4b9b3361

Ответ 1

Внедрить интерфейс 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
}

Ответ 3

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

Сделайте трюк для вас.

Ответ 4

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

Ответ 5

Как насчет расширения List<Contact>

Если вы не хотите расширять какой-либо другой класс, это очень простой, быстрый вариант:

class Contacts :List<Contact>
{   
}