泛型约束
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 泛型约束
{
public class MyClass<T,K,V,W,X>
where T :struct //约束T必须为值类型
where K : class //约束K必须为引用类型
where V : IComparable //约束V必须是实现了IComparable接口
where W : K //要求W必须是K类型,或者K类型的子类
where X :class ,new () // X必须是引用类型,并且要有一个无参的构造函数(对于一个类型有多有约束,中间用逗号隔开)
{
public void SayHello()
{
Console.WriteLine("你好"); //虽然类是一个泛型类,但是那些T,K,V,W,X类型,我可用,也可以不用。
}
public void SayHello(X obj)
{
Console.WriteLine(obj.ToString());
}
}
class Program
{
static void Main(string[] args)
{
//int类型是实现了IComparable接口的,所以第三个参数是可以使用int的
MyClass<int, Stream, int, FileStream, object> mc = new MyClass<int, Stream, int, FileStream, object>();
mc.SayHello(); //输出:你好
mc.SayHello("大家好!"); //输出:大家好
Console.ReadKey();
}
}
}
====================================================
public static List<T> ConvertIListtolist <T>(IList<T> gblist) where T : class
最后面的where T : class是一个参数类型约束,指定T必须是Class类型。
.NET支持的类型参数约束有以下五种:
where T : struct ---- T必须是一个值类型
where T : class ---- T必须是一个引用类型
where T : new() ---- T必须要有一个无参构造函数, (即他要求类型参数必须提供一个无参数的构造函数)
where T : NameOfBaseClass ---- T必须继承名为NameOfBaseClass的类
where T : NameOfInterface ---- T必须实现名为NameOfInterface的接口
例如 class GenericClass2<T, V> where V:T -------- 要求V必须继承于T,这种称为裸类型约束(naked type constraint)
例子
class BaseC
{
int baseInt;
string baseStr;
public void Show()
{
Console.WriteLine("Something");
}
}
//基类约束
class GenericClass3<T> where T : BaseC
{
T ob1;
public void Show()
{
ob1.Show();
}
}
//new()构造函数约束
class GenericClass4<T> where T : new()
{
public T ob1;
public GenericClass4()
{
ob1 = new T();
}
}