.net中的泛型

 

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

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

下面先写一个简单的泛型

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();
        }
    }
}

泛型方法可以出现在泛型或非泛型类型上。需要注意的是,并不是只要方法属于泛型类型,或者甚至是方法的形参的类型是封闭类型的泛型参数,就可以说方法是泛型方法。只有当方法具有它自己的类型参数列表时,才能称其为泛型方法。在下面的代码中,只有方法 G 是泛型方法。
class A 
{
    T G<T>(T arg) {...}
}
class Generic<T> 
{
    T M(T arg) {...}
}



泛型的Where

  泛型的Where能够对类型参数作出限定。有以下几种方式。

  ·where T : struct 限制类型参数T必须继承自System.ValueType。
 
  ·where T : class 限制类型参数T必须是引用类型,也就是不能继承自System.ValueType。

  ·where T : new() 限制类型参数T必须有一个缺省的构造函数

  ·where T : NameOfClass 限制类型参数T必须继承自某个类或实现某个接口。

  以上这些限定可以组合使用,比如: public class Point where T : class, IComparable, new()

例如:
    class Person<T> where T:class
    { 
        
    }

    class Program
    {
        static void Main(string[] args)
        {
           
            Person<int> bb = new Person<int>(); //報錯,
错误 1 类型“int”必须是引用类型才能用作泛型类型或方法“ConsoleApplication1.Person<T>”中的参数“T” 

        }
    }

原文地址:https://www.cnblogs.com/liangxiaofeng/p/5721617.html