这篇文章是对IEnumerable
接口进行基本介绍以及自己写一个链表的代码
首先看看IEnumerable
接口的定义:
//
// 摘要:
// Exposes an enumerator, which supports a simple iteration over a non-generic collection.
[NullableContextAttribute(1)]
public interface IEnumerable
{
//
// 摘要:
// Returns an enumerator that iterates through a collection.
//
// 返回结果:
// An System.Collections.IEnumerator object that can be used to iterate through
// the collection.
IEnumerator GetEnumerator();
}
简而言之IEnumerable
接口中只定义了一个方法 IEnumerator GetEnumerator()
; 这个方法的作用就是 使实现了IEnumerable
接口的类都必须可以遍历(使用foreach
)
我们再来看看IEnumerator
接口是啥样
// Supports a simple iteration over a non-generic collection.
public interface IEnumerator
{
//
// 摘要:
// Gets the element in the collection at the current position of the enumerator.
//
// 返回结果:
// The element in the collection at the current position of the enumerator.
object? Current { get; }
//
// 摘要:
// Advances the enumerator to the next element of the collection.
//
// 返回结果:
// true if the enumerator was successfully advanced to the next element; false if the enumerator has passed the end of the collection.
bool MoveNext();
// Sets the enumerator to its initial position, which is before the first element in the collection.
void Reset();
}
下面总结下实现IEnumerable
接口的作用:
- 可以使用
foreach
语法 - 只有实现了
IEnumerable<T>
接口的类才能使用Linq语句,因为Linq就是一堆IEnumerable<T>
的扩展方法。
下面贴一下自己实现的链表的代码,怎样自定义一个链表,你搞得定吗
public class Node<T> where T : class
{
public T Data { get; set; }
public Node<T> Next { get; set; }
public Node(){}
public Node(T data)
{
Data = data;
Next = null;
}
}
public class MyLinkedList<T> : IEnumerable where T : class
{
public Node<T> Head = new Node<T>();
public void Add(T t)
{
Node<T> node = Head;
while (node.Next != null)
{
node = node.Next;
}
node.Next = new Node<T>(t);
}
public T Get()
{
Node<T> node = Head;
while (node.Next != null)
{
node = node.Next;
}
return node.Data;
}
IEnumerator IEnumerable.GetEnumerator()
{
return new MyEnumerator<T>(Head, Head);
}
}
public class MyEnumerator<T> : IEnumerator where T : class
{
Node<T> head;
Node<T> currnet;
public MyEnumerator(Node<T> head, Node<T> currnet)
{
this.head = head;
this.currnet = currnet;
}
object IEnumerator.Current => currnet;
public bool MoveNext()
{
bool result = false;
if (currnet.Next != null)
{
currnet = currnet.Next;
result = true;
}
return result;
}
public void Reset()
{
currnet = head;
}
}
static void Main(string[] args)
{
MyLinkedList<Person> myLinkedList = new MyLinkedList<Person>();
myLinkedList.Add(new Person
{
Id = 1,
Name = "爷爷",
Age = 78
});
myLinkedList.Add(new Person
{
Id = 2,
Name = "爸爸",
Age = 54
});
myLinkedList.Add(new Person
{
Id = 3,
Name = "儿子",
Age = 32
});
myLinkedList.Add(new Person
{
Id = 4,
Name = "儿子的儿子",
Age = 6
});
foreach (var per in myLinkedList)
{
Node<Person> node = per as Node<Person>;
Console.WriteLine($"Id:{node.Data.Id}, Name:{node.Data.Name}, Age:{node.Data.Age}");
}
Console.ReadKey();
}
运行结果: