.net中的泛型

来源:互联网 发布:淘宝试用协议未同意 编辑:程序博客网 时间:2024/04/28 12:09

泛型把类或方法的类型的确定推迟到实例化该类或方法的时候 ,也就是说刚开始声明是不指定类型,等到要使用(实例化)时再指定类型

泛型可以用于  类、方法、委托、事件等

下面先写一个简单的泛型

public class GenericClass<T>

{

          void SomeMethod(  T   t  )

          {

                   //do something

          }

}

其使用方法如下:

实例化一个类

GenericClass<int> gci=new GenericClass<int>();方法SomeMethod就具有整数类型的参数了

下面写一个例子

using System;
using System.Collections.Generic;
using System.Text;

namespace example
{
    class GenericClass<T>
    {
        public void PrintType(T t)
        {
            Console.WriteLine("Value:{0}    Type:{1}",t,t.GetType());
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            int i = 0;
            GenericClass<int> gci = new GenericClass<int>();
            gci.PrintType(i);

            string s = "hello";
            GenericClass<string> gcs = new GenericClass<string>();
            gcs.PrintType(s);
            Console.ReadLine();
        }
    }
}

原创粉丝点击