第5章 泛型
性能
ArrayList类的Add(Object value)方法,不指定参数类型,操作值类型参数是需要拆箱装箱
ArrayList list=new ArrayList();
list.Add(12);
int i=(int)list[0];
List<T>类的Add(Titem)方法,需要指定T的类型,不需要拆箱装箱
var list=new List<int>();
list.Add(12);
int i=list[0];
泛型的功能
默认值
default关键字
int i=default(int);//0
string str=default(string);//null
default用于泛型中
public T GetDefaultValue()
{
return default(T);//根据传入类型返回默认值
}
约束
where关键字,只能用于泛型?
public class DocumentManager<TDocument>
where TDocument:IDocument//给定约束,传入的TDocument必须实现IDocument接口
{
}
泛型支持的集中约束类型
约束
说明
where T:struct
对于结构约束,类型T必须是值类型
where T:class
T必须是引用类型
where T:IFoo
T必须实现接口IFoo
where T:Foo
T必须派生自Foo类
where T:new()
这是一个构造函数约束,T必须有一个默认构造函数,不能约束有参构造
where T1:T2
T1必须派生自T2,该约束也称为裸类型约束
可以合并多个约束
where T:IFoo, new()
继承
没什么特别的
静态成员
只能在类的一个实例中共享
public class StaticDemo<T>
{
public static int x;
}
StaticDemo<int>.x=4;
StaticDemo<string>.x=5;
这样等于存在两组静态字段
协变和抗变(没懂)
协变抗变是指参数和返回值的类型进行转换
public interface IIndex<out T>//接口泛型的协变
public interface IDisplay<in T>//接口泛型的抗变