[学习笔记]C#高级编程(第5章 泛型)

第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>//接口泛型的抗变

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值