我正在学习关于IEnumerator和IEnumerable的知识,它们一般都是c#的新手。我正在尝试从这个代码示例中学习:
class colors : IEnumerable , IEnumerator
{
private string[] cols;
private int iCurrent;
public colors()
{
cols = new string[] { "Red", "White", "Blue", "Yellow" };
iCurrent = -1;
}
public IEnumerator GetEnumerator()
{
return (IEnumerator)this;
}
}代码中还有更多内容,但我的问题是关于最后一行的。
首先,我不明白将返回什么,也不完全理解代码中的这一行。是颜色IEnumerator类型,还是字符串类型。这个指向的是什么?
其次,在CPP中,我记得我创建了迭代器,例如:
std::map<object>::iterator it,然后我使用它添加it.begin(),it.end()循环。现在我明白了,在我创建了这个迭代器/IEnumerator之后,C#有了foreach循环,这将使我不必面对所有这些问题。但是,是否有一种更容易/更快地创造它们的方法呢?
发布于 2015-10-01 23:52:47
是否有一种更容易/更快创建枚举器的方法?是的,用yield return语句。https://msdn.microsoft.com/en-us/library/9k7k7cf0.aspx声明一个返回IEnumerable的方法,并在其中进行所有的迭代。不需要MoveNext、重置或电流。
发布于 2015-10-01 23:54:27
实现IEnumerator应该留给您自己的自定义容器来实现(就像在C++中实现哈希集一样)。IEnumerable返回Object类型的值,由容器实现,足以使用foreach。IEnumerable<string>是更强类型的版本,很可能是您在这里想要的。
示例中使用的字符串数组允许将其内容枚举为Strings。下面是一些使用IEnumerator和IEnumerator<string>的示例,而不是自己实现枚举数;也许它们可以帮助您达到您想要的目的:
using System;
using System.Collections;
using System.Collections.Generic;
public class Colors : IEnumerable, IEnumerator
{
private readonly string[] cols = new[] { "Red", "White", "Blue", "Yellow" };
public IEnumerator GetEnumerator()
{
return cols.GetEnumerator();
}
}
public class Colors2
{
private readonly string[] cols = new[] { "Red", "White", "Blue", "Yellow" };
public IEnumerable<string> Colors
{
get { return cols; }
}
}
class Program
{
static void Main(string[] args)
{
Test();
Test2();
Test3();
}
private static void Test()
{
var colors = new Colors();
foreach (var c in colors)
{
// c is of type Object here because it's IEnumerable.
Console.WriteLine(c);
}
}
private static void Test2()
{
var colors2 = new Colors2();
foreach (var c in colors2.Colors)
{
// c is of type String here because it's IEnumerable<string>.
Console.WriteLine(c);
}
}
private static void Test3()
{
foreach (var c in new[] { "Red", "White", "Blue", "Yellow" })
{
// c is of type String here.
Console.WriteLine(c);
}
}
}https://stackoverflow.com/questions/32898215
复制相似问题