如何在C#中使类成为IEnumerable? [英] How to make the class as an IEnumerable in C#?

查看:54
本文介绍了如何在C#中使类成为IEnumerable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此我有一个类和一个通用列表,但它是私有的。

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) .... ;

像这样(不起作用):

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

在上面的示例中,Contact类实例c必须从通讯录中返回每个项目( c)

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

我该怎么做?我知道它必须具有IEnumerable并具有收益回报,但是在哪里声明呢?

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

推荐答案

实现IEnumerable接口:

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
}

这篇关于如何在C#中使类成为IEnumerable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆