如何使用的foreach关键字的自定义对象在C# [英] How to use foreach keyword on custom Objects in C#

查看:217
本文介绍了如何使用的foreach关键字的自定义对象在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以分享使用的foreach 关键字与自定义对象的一个​​简单的例子?

Can someone share a simple example of using the foreach keyword with custom objects?

推荐答案

由于标签,我假设你在.NET中的意思是 - 我会选择谈论C#,因为这是我所知道的关于

Given the tags, I assume you mean in .NET - and I'll choose to talk about C#, as that's what I know about.

的foreach 语句(通常)使用的IEnumerable 的IEnumerator 或他们的共通表兄弟。该形式的语句:

The foreach statement (usually) uses IEnumerable and IEnumerator or their generic cousins. A statement of the form:

foreach (Foo element in source)
{
    // Body
}

其中,工具的IEnumerable<富> 是的大致的等价于:

where source implements IEnumerable<Foo> is roughly equivalent to:

using (IEnumerator<Foo> iterator = source.GetEnumerator())
{
    Foo element;
    while (iterator.MoveNext())
    {
        element = iterator.Current;
        // Body
    }
}



注意的IEnumerator<富> 设置在年底,不过声明中退出。这是迭代器块重要

Note that the IEnumerator<Foo> is disposed at the end, however the statement exits. This is important for iterator blocks.

要落实的IEnumerable< T> 的IEnumerator< T> 自己,最简单的方法是使用迭代器块。而不是写在这里所有的细节,它可能最好还是请您先 href=\"http://www.manning.com/skeet\">第六章,这是一个免费下载。第6章的全部是迭代器。我有我的C#在深入现场另一对夫妇的文章,也:

To implement IEnumerable<T> or IEnumerator<T> yourself, the easiest way is to use an iterator block. Rather than write all the details here, it's probably best to just refer you to chapter 6 of C# in Depth, which is a free download. The whole of chapter 6 is on iterators. I have another couple of articles on my C# in Depth site, too:

  • Iterators, iterator blocks and data pipelines
  • Iterator block implementation details

作为一个简单的例子,但:

As a quick example though:

public IEnumerable<int> EvenNumbers0To10()
{
    for (int i=0; i <= 10; i += 2)
    {
        yield return i;
    }
}

// Later
foreach (int x in EvenNumbers0To10())
{
    Console.WriteLine(x); // 0, 2, 4, 6, 8, 10
}

要落实的IEnumerable< T> 的类型,你可以这样做:

To implement IEnumerable<T> for a type, you can do something like:

public class Foo implements IEnumerable<string>
{
    public IEnumerator<string> GetEnumerator()
    {
        yield return "x";
        yield return "y";
    }

    // Explicit interface implementation for nongeneric interface
    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator(); // Just return the generic version
    }
}

这篇关于如何使用的foreach关键字的自定义对象在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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