C#泛型约束6种使用方法

c# where泛型约束:在定义泛型的时候,我们可以使用where限制参数的范围
共有六种类型的约束:
1:T:类(类型参数必须是引用类型,这一点也适用于任何类,接口,委托或数组类型)
class MyClass<T,U>
    where T:class //约束T必须为“引用 类型{}”
    where U:struct //约束U必须为“值 类型”
    {
        //...
    }
2:T:结构(类型参数必须是值类型,可以指定除Nullable以外的任何值类型)
class MyClass<T,U>
    where T:class //约束T必须为“引用 类型{}“
    where U:struct //约束U必须为“值类型”
3:T:new()(类型参数必须具有无参数的公共构造函数。当与其它一起使用时,new()约束必须最后指定
class EmployeeList<T> where T:Employee,IEmployee,System.IComparable<T>,new()
{...}
4:T:<基类名>(类型参数必须是指定的基类或派生自指定的基类)
class Employee()
class GenericList<T> where T:Employee
5:T:<接口名称>(参数必须是指定的接口或实现指定的接口。可以指定多个接口约束。约束接口也可以是泛型)
interface IMyInterface{}
class Dictionary<TKey,TVal>
    where TKey:IComparable,IEnumerable
    where TVal:IMyInterface
    {...}
6:T:U(为T提供的类型参数必须是为U提供的参数或派生为U提供的参数,也就是说T和U的参数必须一样)
class List<T>
{
    void Add<U>(List<U> items) where U:T //这种where U:T泛型约束方式以前还没有看到,此处的要求就是说泛型参数U必须来自T或派生自T类型
}        
a)可用于类
public class MyGenericClass<T> where T:IComparable{}//T必须是IComparable接口类型或接口的实现类
b)可用于方法
public boo MyMethod<T>(T t) where T:IMyInterface{}//T类型必须是IMyInterace接口类型或其实现类
c)可用于委托
public delegate T MyDelegate<T>() where T:new()//T类型必须具有无参数的公共构造函数,当new()与其它约束一起使用时,必须要放在最后
public delegate void MyDelegate<T>(T args) where T:IComparer,new()

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章