C#泛型初探

下面这个例子创建的是链表的泛型版本。泛型类的定义与一般类类似,只是要使用泛型类型声明。之后,泛型类型就可以在类中用作一个字段成员,或者方法的参数类型。可以返回和设置泛型类型,所以属性Prev和Next的类型是LinkedListNode.

除了IEnumerable接口,还有一个泛型版本IEnumerable.IEnumerable派生自IEnumerable,添加了返回IEnumeraotr的GetEnumerator()方法,LinkedList实现泛型接口IEnumerable.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ProCSharp;

namespace ProCSharp
{
    public class LinkedListNode
    {
        public LinkedListNode(T value)
        {
            this.Value = value;
        }
        //包含一个属性Value,该属性用构造函数初始化
        public T Value{get;private set;}
        //LinkedListNode类包含对链表中下一个元素和上一个元素的引用,
        //这些元素都可以从属性中访问
        public LinkedListNode Next { get; internal set; }
        public LinkedListNode Prev { get; internal set; }
    }

    public class LinkedList : IEnumerable
    {
        public LinkedListNode First { get; private set; }
        public LinkedListNode Last { get; private set; }
        public LinkedListNode AddLast(T node)
        {
            var newNode = new LinkedListNode(node);
            if (First==null)
            {
                First = newNode;
                Last = newNode;
            }
            else
            {
                LinkedListNode previous = Last;
                Last.Next = newNode;
                Last = newNode;
                Last.Prev = previous;
            }
            return newNode;
        }

        public IEnumerator GetEnumerator()
        {
            LinkedListNode current = First;

            while(current!=null)
            {
                yield return current.Value;
                current = current.Next;
            }
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
    public class MainEntry
    {
        public static void Main()
        {
            var list = new LinkedList();
            list.AddLast(2);
            list.AddLast(5);
            list.AddLast(8);
            list.AddLast(100);
            foreach(int i in list)
            {
                Console.WriteLine(i);
            }
            var list2 = new LinkedList();
            list2.AddLast("Tsinghua University");
            list2.AddLast("Peking University");
            list2.AddLast("Zhejiang University");
            foreach(string s in list2)
            {
                Console.WriteLine(s);
            }
            Console.ReadLine();

        }
    }
}


你可能感兴趣的:(C#,泛型,c#,链表)