c# - 如何在 C# 中将类设为 IEnumerable?

标签 c# class ienumerable

所以我在其中有一个类和一个通用列表,但它是私有(private)的。

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

我想让类(class)像这样工作:

foreach(Contact in contacts) .... ;

像这样(不工作):

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

在上面的示例中,Contact 类实例 c 必须返回联系人中的每个项目(c 的私有(private)成员)

我该怎么做?我知道它必须是带有 yield return 的 IEnumerable,但是在哪里声明呢?

最佳答案

实现IEnumerable接口(interface):

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# - 如何在 C# 中将类设为 IEnumerable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13135443/

相关文章:

c# - 有没有非常快速的校验和生成算法?

c# - 具有动态自定义参数的 MVC 下拉列表

c# - .Net 如何加载类?

javascript - JavaScript 类中 undefined variable

python - 对 Python 类和实例变量的复合赋值

c# - 开发与生产中的 settings.settings connectionstring

c# - 如果使用 Visual C++ Compiler November 2013 CTP,所有依赖项是否也需要用它编译?

c# - 我如何随机订购 IEnumerable<>?

c# - IEnumerable.Max() 是最快的方法吗?

c# - 比较 IEnumerable<T> 的类型