基本信息
源码名称:泛型(generic)是C#语言2.0和通用语言运行时(CLR)的一个新特性
源码大小:0.13M
文件格式:.7z
开发语言:C#
更新时间:2020-09-08
   友情提示:(无需注册或充值,赞助后即可获取资源下载链接)

     嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):78630559

本次赞助数额为: 2 元 
   源码介绍




using System;

using System.Collections.Generic;

 

public class MyList<T> //type parameter T in angle brackets

    {

        private Node head;

// The nested type is also generic on T.

        private class Node          

        {

            private Node next;

//T as private member data type:

            private T data;         

//T used in non-generic constructor:

            public Node(T t)        

            {

                next = null;

                data = t;

            }

            public Node Next

            {

                get { return next; }

                set { next = value; }

            }

//T as return type of property:

            public T Data           

            {

                get { return data; }

                set { data = value; }

            }

        }

        public MyList()

        {

            head = null;

        }

//T as method parameter type:

        public void AddHead(T t)    

        {

            Node n = new Node(t);

            n.Next = head;

            head = n;

        }

 

        public IEnumerator<T> GetEnumerator()

        {

            Node current = head;

 

            while (current != null)

            {

                yield return current.Data;

                current = current.Next;

            }

        }

    }

 

下面的示例代码演示了客户代码如何使用泛型类MyList<T>,来创建一个整数表。通过简单地改变参数的类型,很容易改写下面的代码,以创建字符串或其他自定义类型的表。

 

class Program

    {

        static void Main(string[] args)

        {

//int is the type argument.

           MyList<int> list = new MyList<int>();

            for (int x = 0; x < 10; x )

                list.AddHead(x);

 

            foreach (int i in list)

            {

                Console.WriteLine(i);

            }

            Console.WriteLine("Done");

        }

    }