开篇先说一下泛型的优点
1、可以通过一个方法实现多种参数的调用
2、性能无损失
3、生命方法的时候没有指定类型,调用的时候指定,这就是一种延迟
泛型的创建举例
泛型方法
public static void Show<T>(T t)
{
Console.WriteLine("参数类型是:{0}",typeof(T));
}
调用方法
string sValue = "这里是一串汉字";
Generic.Show<string>(sValue);
Generic.Show(sValue);//这样<string>不写 系统也会根据传入参数自行判断类型
泛型接口
public interface Iinterface<T>
{
void Say();
}
注:继承泛型接口是有限制的,有2种方式
第一种:类也是泛型
public class NewClass<T> : Iinterface<T>
{
public void Say()
{
}
}
第二种:直接指定接口泛型参数类型
public class NewClass:Iinterface<string>
{
public void Say()
{
}
}
泛型类
public class Tclass<T>
{
}
泛型委托
public delegate void Tdelegate<T>(T t);
多泛型参数
泛型参数不是只能设置一个T,而且也不一定必须叫T ,T只是一个占位符而已 并且可以多个
public static void Show<T, S, W, Y>(T t, S s, W w, Y y)
{
}
泛型返回值
public T ShowIs<T>()
{
return default(T);//根据类型返回默认值
}
下面代码表示,对T参数进行约束 传入的需要是一个引用类型参数
public static void Show1<T>(T t)
where T:class
{
Console.WriteLine("参数类型是:{0}", typeof(T));
}
如果这个时候 传入一个值类型 就会报错了,如图
当然 也可以约束只能传入一个值类型,如下
public static void Show2<T>(T t)
where T : struct//需要传入一个值类型
{
Console.WriteLine("参数类型是:{0}", typeof(T));
}
或者是一个自定义类
public class People
{
}
public static void Show3<T>(T t)
where T : People//需要传入People类型或者他的子类
{
Console.WriteLine("参数类型是:{0}", typeof(T));
}
或者继承某一个接口
public interface Iinterface1
{
}
public static void Show3<T>(T t)
where T : Iinterface1//需要传入的类型继承该接口
{
Console.WriteLine("参数类型是:{0}", typeof(T));
}
或者必须有一个无参构造函数(可以约束无参构造函数但不可以约束有参数的构造函数)
有new()约束 还可以创建T对象哦
public static void Show3<T>(T t)
where T : new()//需要传入的类型有无参构造函数
{
T t = new T();//设置了new()约束后可以创建对象哦
Console.WriteLine("参数类型是:{0}", typeof(T));
}
当然。也可以设置多个约束哦
public static void Show3<T>(T t)
where T : People, Iinterface1, Iinterface2,new()//多约束类型
{
Console.WriteLine("参数类型是:{0}", typeof(T));
}
多约束类型需要注意 他是由 一个类+多个接口+一个new() 这种顺序组成的,可以减少,但是顺序不能乱