C#泛型

定义:通过泛型可以定义类型安全类,而不会损害类型安全、性能或工作效率。

泛型的好处

1、同样的代码,可以通过任何类型来重用它,减少重复代码

2、编译器支持和类型安全

3、不会强行对值类型进行装箱和取消装箱,或者对引用类型进行向下强制类型转换,性能提高。

泛型继承:
1、泛型类继承中,父类的类型参数已被实例化,这种情况下子类不一定必须是泛型类;
2、父类的类型参数没有被实例化,由子类指定,也就是说父类和子类都是泛型类,并且二者有相同的类型参数;

泛型写法:
泛型类

public class TestChild : Test< string, int>{ }

public class TestChild< T, S> : Test< T, S> { }

public class TestChild< T, S> : Test< String, int> { }
泛型方法:C#的泛型机制只支持在方法申明上包含类型参数,也即是泛型方法

1
2
3
4
5
6
public T getvalue<T>(T t)
{
return t;
}
使用:
Int a = getvalue<Int>(10);

泛型接口:

public interface IList
{
T[] GetElements();
}
泛型委托:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class MyClass<T>
{
public delegate void GenericDelegate(T t);
public void SomeMethod(T t)
{
}
}

public GenericMethodDemo()
{
MyClass<int> obj = new MyClass<int>();
MyClass<int>.GenericDelegate del;
del = new MyClass<int>.GenericDelegate(obj.SomeMethod);
del(3);
}

泛型约束:C#中的泛型只支持显示的约束,因为这样才能保证C#所要求的类型安全,但显示的约束并非时必须的,如果不加约束,泛型类型参数将只能访问System.Object类型中的公有方法。“显式约束”由where子句表达,可以指定“基类约束”,“接口约束”,“构造器约束”,“值类型/引用类型约束”共四种约束

构造器约束:

public static T CreateObject(out int objectId) where T : new()
public class CSingleton where T : new()
基类约束,还包括基类和接口:

public T FindControl(string name) where T : Component
public class CSingleton where T : IComparable
值约束:

public class MyClass where T : struct { }
引用约束:

public class MyClass where T : class { }
约束组合:

public class MyClass where T : IComparable, new() { }
public class MyClass where T : struct, IComparable { }
public class MyClass where T : B, IComparable, ICloneable { }
public class MyClass<T, U> where T : IComparable where U : class { }
约束 说明
T:struct 类型参数必须是值类型。可以指定除 Nullable 以外的任何值类型。与接口约束同时使用,在最前面(不能与基类约束,构造函数约束一起使用)
T:class 类型参数必须是引用类型,包括任何类、接口、委托或数组类型。
T:new() 类型参数必须具有无参数的公共构造函数。当与其他约束一起使用时,new() 约束必须最后指定。
T:<基类名> 类型参数必须是指定的基类或派生自指定的基类。
T:<接口名称> 类型参数必须是指定的接口或实现指定的接口。可以指定多个接口约束。约束接口也可以是泛型的。
T:U 为 T 提供的类型参数必须是为 U 提供的参数或派生自为 U 提供的参数。这称为裸类型约束.