如何在 C# 中的自定义对象上使用 foreach 关键字 [英] How to use foreach keyword on custom Objects in 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
}
其中source
实现IEnumerable
大致等价于:
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
或 IEnumerator
,最简单的方法是使用迭代器块.与其在这里写下所有的细节,不如让你参考深入了解 C# 的第 6 章,这是一个免费下载.整个第 6 章都是关于迭代器的.我的 C# in Depth 网站上还有另外几篇文章:
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:
举个简单的例子:
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
,您可以执行以下操作:
To implement IEnumerable<T>
for a type, you can do something like:
public class Foo : 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
}
}
这篇关于如何在 C# 中的自定义对象上使用 foreach 关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!