其他
一文详解枚举器和迭代器!
作者 | 喵叔
责编 | 胡巍巍
出品 | 程序人生(ID:coder_life)
{
public object Current
{
get { return true; }
}
public bool MoveNext()
{
return false;
}
public void Reset()
{
//more code
}
}
{
public IEnumerator GetEnumerator()
{
IEnumerable<string> myEnumerable = null;
return myEnumerable.GetEnumerator();
}
}
{
using (var item = "abcdefg".GetEnumerator())
{
while (item.MoveNext())
{
var _char = item.Current;
Console.WriteLine(_char);
}
}
Console.Read();
}
strList.Add("张三");
strList.Add("李四");
strList.Add("王五");
strList.Add("赵六");
{
foreach (int item in demo(5))
{
Console.WriteLine(item);
}
Console.Read();
}
static IEnumerable<int> demo(int demoCount)
{
int data = 0;
for (int i = 0; i < demoCount; i++)
{
yield return data;
data = data + 1;
}
}
{
foreach(int item in demo)
{
Console.WriteLine(item);
}
}
static IEnumerable<int> Foo()
{
yield return 1;
yield return 2;
yield return 3;
}
{
yield return 1;
yield return 2;
yield return 3;
yield break;
yield return 4;
}
{
static void Main(string[] args)
{
foreach (int fib in GetNum(Fibs(12)))
Console.WriteLine(fib);
Console.Read();
}
static IEnumerable<int> Fibs(int count)
{
int result = 0;
for (int i = 0; i < count; i++)
{
yield return result;
result = result + i;
}
}
static IEnumerable<int> GetNum(IEnumerable<int> sequence)
{
foreach (int x in sequence)
{
yield return x;
}
}
}