supegong  

<1>不使用泛型的情况:

ArrayList list = new ArrayList();
list.Add(44);   // 装箱

int i1 = (int)list[0];//折箱

list.Add(new MyClass());(可增加为其它的任何对象,但不能用foreach运算)

Add()方法定义为需要把一个对象作为参数,所以要装箱一个整数类型。在读取ArrayList中的值时,要进行拆箱,把对象转换为整数类型。

<2>使用泛型的情况:(可以在编译时就找到错误,即在编译时实现类型安全)

List<int> list = new List<int>();
list.Add(44);   // 没有装箱 - value types are stored in the List<int>

int i1 = list[0]; //没有折箱

list.Add(new MyClass());   // 编译出错

List<T>类的泛型类型定义为int(List<T>类用一个int类型实例化),所以int类型在JIT编译器动态生成的类中使用,不再进行装箱和拆箱操作(List内的值为int型)

a.public class MyList<T>创建了一个称为MyList泛型类。为把它参数化,插入了一个尖括号。在<>内的T代表了实际的当使用该类时要指定的类型。

b.MyList1<int> myIntList = new MyList1<int>();MyList<int>是与MyList<double>不同的类

c. 不能在参数化类型的实例中使用象==,!=或<等运算符,如:T obj1,obj2;if(obj1==obj2)

<3>简单链表示例

a.泛型类的定义与一般类类似,只是要使用泛型类型声明

b.使用泛型类LinkedList<T>,可以用int类型实例化它

c.泛型类型就可以在类中用作一个字段成员,或者方法的参数类型

public class LinkedListNode<T>//泛型类的定义与一般类类似,只是要使用泛型类型声明(LinkedListNode类用一个泛型类型T声明。)

    {

        private T value;//泛型类型就可以在类中用作一个字段成员,或者方法的参数类型,如下行。

        public LinkedListNode(T value)//不用LinkedListNode<T>(T value)

        {

            this.value = value;

        }

        public T Value//Value属性为接受和返回T类型的对象。

        {

            get { return value; }

        }

 

 

        private LinkedListNode<T> next;

        public LinkedListNode<T> Next

        {

            get { return next; }

            internal set { next = value; }

        }

 

 

        private LinkedListNode<T> prev;

        public LinkedListNode<T> Prev

        {

            get { return prev; }

            internal set { prev = value; }

        }

    }

 

    public class LinkedList<T> : IEnumerable<T>

    {

        private LinkedListNode<T> first;

        public LinkedListNode<T> First

        {

            get { return first; }

        }

 

        private LinkedListNode<T> last;

        public LinkedListNode<T> Last

        {

            get { return last; }

        }

 

        public LinkedListNode<T> AddLast(T node)

        {

            LinkedListNode<T> newNode = new LinkedListNode<T>(node);

            if (first == null)

            {

                first = newNode;

                last = first;

            }

            else

            {

                last.Next = newNode;

                last = newNode;

            }

            return newNode;

        }

        public IEnumerator<T> GetEnumerator()

        {

            LinkedListNode<T> current = first;

            while (current != null)

            {

                yield return current.Value;

                current = current.Next;

            }

        }

        IEnumerator IEnumerable.GetEnumerator()

        {

            return GetEnumerator();

        }      

    }

   

 

    class Class14

    {

        public static void Main()

        {

            LinkedList<int> list1 = new LinkedList<int>();//使用泛型类LinkedList<T>,可以用int类型实例化它

            list1.AddLast(2);

            list1.AddLast(4);

            //list1.AddLast("6");

            foreach (int i in list1)

            {

                Console.WriteLine(i);

            }

 

        }

    }

<4>使用泛型文档管理器的示例

  1. 通过default关键字,将null赋予引用类型,将0赋予值类型。
  2. 如果泛型类需要调用泛型类型上的方法,就必须添加约束。

public interface IDocument

    {

        string Title { get; set; }

        string Content { get; set; }

    }

    public class Document : IDocument

    {

        public Document()

        {

        }

        public Document(string title, string content)

        {

            this.Title = title;

            this.Content = content;

        }

        public string Title { get; set; }

        public string Content { get; set; }

      

    }

    //上面为一个Document类,将此类放入一个队列Queue中

 

    public class DocumentManager<T>

        where T : IDocument//如果泛型类需要调用泛型类型上的方法,就必须添加约束。使用后可以用T.Title,T.Content

    {

        private readonly Queue<T> documentQueue = new Queue<T>();//定义一个队列(先进先出)

        public void AddDocument(T doc)

        {

            lock (this)

            {

                documentQueue.Enqueue(doc);

            }

        }

        public T GetDocument()

        {

            T doc = default(T);//通过default关键字,将null赋予引用类型,将0赋予值类型。

            lock (this)

            {

                doc = documentQueue.Dequeue();

            }

            return doc;

        }

 

        public void DisplayAllDocuments()

        {

            foreach (T doc in documentQueue)

            {

                Console.WriteLine(doc.Title);//T类型必须执行IDocument接口,Title为IDocument的属性

            }

        }

 

 

        public bool IsDocumentAvailable

        {

            get { return documentQueue.Count > 0; }

        }

    }

 

 

    class Class15

    {

        public static void  Main()

        {

            DocumentManager<Document> dm = new DocumentManager<Document>();

            dm.AddDocument(new Document("Title A", "Sample A"));//参数为一个传入的Document类型

            dm.AddDocument(new Document("Title B", "Sample B"));

            dm.DisplayAllDocuments();

           

            if (dm.IsDocumentAvailable)

            {

                Document d = dm.GetDocument();

                Console.WriteLine(d.Content);

            }

        }

    }

<5>泛型方法、泛型委托

       实现了IAccount接口的类可以实现Algorithm.AccumulateSimple<Account>(accounts)方法

     注:此方法不在接口中,而是在另一个类中。

public interface IAccount

    {

        decimal Balance { get; }

        string Name { get; }

    }

 

    public class Account:IAccount

    {

        private string name;

        public string Name

        {

            get

            {

                return name;

            }

        }

        private decimal balance;

        public decimal Balance

        {

            get

            {

                return balance;

            }

        }

        public Account(string name, Decimal balance)

        {

            this.name = name;

            this.balance = balance;

        }

    }

 

    public static class Algorithm

    {

     //只要实现了IAccount接口,则可以调用此泛型方法

        public static decimal AccumulateSimple<T>(IEnumerable<T> e)

            where T:IAccount

        {

            decimal sum = 0;

            foreach (T a in e)

            {

                sum += a.Balance;

            }

            return sum;

        }

     //泛型委托:如下黑体为调用的泛型委托(此委托两个参数为输入值和输出值)

    

        public delegate TSummary Action<TInput, TSummary>(TInput t, TSummary u);

        public static TSummary Accumulate<TInput, TSummary>(IEnumerable<TInput> coll,Action<TInput, TSummary> action)

        {

            TSummary sum = default(TSummary);

            foreach (TInput input in coll)

            {

                sum = action(input, sum);//以上次累加的和来返回本次累加的和。

            }

            return sum;

        }

 

    }

    class Class17

    {

        static public decimal a(Account a, decimal d)

        { return a.Balance + d; }

 

        static void Main(string[] args)

        {

            List<Account> accounts = new List<Account>();

           

            accounts.Add(new Account("Christian", 2));

            accounts.Add(new Account("Sharon",2));

            accounts.Add(new Account("Katie",3));

            //decimal amount = Algorithm.AccumulateSimple(accounts);

            //decimal amount = Algorithm.AccumulateSimple<Account>(accounts);

            decimal amount = Algorithm.Accumulate<Account, decimal>(accounts, a);

            Console.WriteLine(amount);

 

 

            }

    }

posted on 2011-03-08 16:10  supegong  阅读(193)  评论(0)    收藏  举报