using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace test
{
public class Node<T>
{
public T Value { get; private set; }
public Node<T> Next { get; internal set; }
public Node<T> Pre { get; internal set; }
public Node(T value)
{
this.Value = value;
}
}
class TheList<T>:IEnumerable<T>
{
public Node<T> First { get; private set; }
public Node<T> Last { get; private set; }
public void AddLast(T value)
{
Node<T> newNode = new Node<T>(value);
if (this.First == null)
{
this.First = newNode;
newNode.Pre = this.Last;
this.Last = this.First;
}
else
{
Node<T> pervious = this.Last;
this.Last.Next = newNode;
this.Last = newNode;
this.Last.Pre = pervious;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public IEnumerator<T> GetEnumerator()
{
Node<T> current = this.First;
while (current != null)
{
yield return current.Value;
current = current.Next;
}
}
}
class Program
{
public static void Main(string[] args)
{
TheList<int> list = new TheList<int>();
list.AddLast(10);
list.AddLast(20);
list.AddLast(30);
foreach(int val in list)
{
Console.WriteLine(val);
}
return;
}
};
}
c# iterator原理:
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace test
{
class Enumerator :
System.Collections.Generic.IEnumerator<string>,
System.Collections.IEnumerator,
System.IDisposable
{
private int state_;
private string current_;
public Enumerator(int state = 0)
{
this.state_ = state;
}
bool System.Collections.IEnumerator.MoveNext()
{
Console.WriteLine("move next");
switch (this.state_)
{
case 0:
{
this.current_ = "hello";
this.state_ = 1;
return true;
}
case 1:
{
this.current_ = "word";
this.state_ = 2;
return true;
}
case 2:
break;
}
return false;
}
void System.Collections.IEnumerator.Reset()
{
Console.WriteLine("throw");
throw new NotSupportedException();
}
string System.Collections.Generic.IEnumerator<string>.Current
{
get
{
Console.WriteLine("--------------------");
return this.current_;
}
}
object System.Collections.IEnumerator.Current
{
get
{
Console.WriteLine("get Current");
return this.current_;
}
}
void IDisposable.Dispose()
{
Console.WriteLine("stop");
return;
}
}
class TheIterator
{
public IEnumerator GetEnumerator()
{
return new Enumerator();
}
}
class test
{
public static void Main(string[] args)
{
TheIterator itr = new TheIterator();
foreach(var val in itr)
{
Console.WriteLine(val);
}
return;
}
}
}