C#2.0 泛型

1.泛型类

定义:

class Test<T> 注:T是占位符可以随便写
{
      public T data; 注:定义一个T类型的字段
      public Test(T obj) 注:定义一个T类型的方法
      {
             this.data = obj;
      }
}

实例化泛型类

private static void Main(string[] args)
{
Test<int> test = new Test<int>(3); 
Console.WriteLine(test.data);

Console.ReadKey();
}

2.泛型方法

定义:

public static void Swap<T>(ref T a, ref T b)  值:定义一个泛型方法,ref 是指引用返回值是否作为调用方欲修改的引用被存储在本地
{
      a = b;
}

private static void Main(string[] args)

{

int a = 1;
int b = 2;
Swap<int>(ref a, ref b); 注:传递int类型的两个值
Console.Write(a);

Console.ReadKey();
}

 3.泛型约束

public static void Swap<T>(ref T a, ref T b)  where T:struct 注:传递类型必须是值类型
{
      a = b;
}

public static void Swap<T>(ref T a, ref T b)  where T:class注:传递类型必须是引用类型
{
      a = b;
}

public static void Swap<T>(ref T a, ref T b)  where T:new()注:传递类型参数必须具有无参数的公共构造函数。当与其他约束一起使用时,new() 约束必须最后指定。
{
      a = b;
}

public static void Swap<T>(ref T a, ref T b)  where T:<基类名>注:传递类型参数必须是指定的基类或派生自指定的基类。
{
      a = b;
}

public static void Swap<T>(ref T a, ref T b)  where T:<接口名称>注:传递类型参数必须是指定的接口或实现指定的接口。可以指定多个接口约束。约束接口也可以是泛型的。
{
      a = b;
}

public static void Swap<T>(ref T a, ref T b)  where T:U  注:为 T 提供的类型参数必须是为 U 提供的参数或派生自为 U 提供的参数。这称为裸类型约束。
{
      a = b;
}

原文地址:https://www.cnblogs.com/zhang1999/p/7419517.html