废话不多说,直接贴代码:
MyCustomerList.cs
public class MyCustomerList: IEnumerable { private class Node { public Node(T data) { _data = data; _next = null; } private T _data; public T Data { get { return _data; } set { _data = value; } } private Node _next; public Node Next { get { return _next; } set { _next = value; } } } private Node _head; public MyCustomerList() { _head = null; } /// /// 添加到集合的头部 /// /// public void AddToHead(T data) { Node current = new Node(data); current.Next = _head; _head = current; } ////// 添加到集合的尾部 /// /// public void AddToLast(T data) { Node current = new Node(data); Node last = GetLastNode(); if (last == null) { //集合中目前还没有元素 _head = new Node(data); } else { last.Next = current; } } private Node GetLastNode() { Node last = _head; while(last != null && last.Next != null) { last = last.Next; } return last; } public IEnumeratorGetEnumerator() { Node current = _head; while(current != null) { yield return current.Data; current = current.Next; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } }
Program.cs
public class Program { static void Main(string[] args) { MyCustomerList myList = new MyCustomerList (); myList.AddToLast(10); myList.AddToLast(20); myList.AddToLast(30); myList.AddToLast(40); Show(myList); myList.AddToHead(5); myList.AddToHead(3); Show(myList); MyCustomerListteachers = new MyCustomerList (); teachers.AddToLast(new Teacher() { Name = "张三", Age = 26, Birthday = new DateTime(1985,8,7) }); teachers.AddToLast(null); teachers.AddToLast(new Teacher() { Name = "李四", Age = 27, Birthday = new DateTime(1984, 8, 7) }); teachers.AddToLast(new Teacher()); Show(teachers); Console.ReadLine(); } static void Show (MyCustomerList myList) { Console.WriteLine("\n准备遍历集合中的内容:"); foreach (var item in myList) { Console.WriteLine(item); } Console.WriteLine("遍历结束\n"); } } public class Teacher { public Teacher() { } public Teacher(string name, int age, DateTime birthday) { this.Name = name; this.Age = age; this.Birthday = birthday; } public string Name { get; set; } public int Age { get; set; } public DateTime Birthday { get; set; } public override string ToString() { return string.Format("大家好,我叫 {0}, 今年 {1} 岁,出生日期:{2}",Name,Age,Birthday); } }
运行截图:
谢谢浏览!