志在指尖
用双手敲打未来

C#泛型

1、引入泛型
泛型不是一个简略的语法糖,是结构晋级支撑的
List便是泛型,为什么要有泛型?
List是一个调集,或许是一组int,也或许是一组string,泛型便是用一个东西来满座多种不同类型的需求的。
2、泛型办法
办法名称后面加上尖括号,里面是类型参数,类型参数实际上便是一个类型T声明,办法就能够用这个类型T了。泛型声明办法时,并没有写死类型,T是什么,并不知道,T要等着调用的时分才指定。正式由于没有写死,才拥有了无限的或许。
泛型的规划思维–推延声明:推延全部能够推延的,全部能晚点再做的事,就晚一点再做。泛型不是一个简略的语法糖,是结构晋级支撑的。泛型办法的功能跟一般办法一直,是最好的,而且还能一个办法满意多个不同类型。C#
下面来看下代码是怎样写的:
publicstaticvoidShow(TtParameter)//,Tt=default(T{
Console.WriteLine(“Thisis{0},parameter={1},type={2}”,typeof(CommonMethod),tParameter.GetType().Name,tParameter);
}
泛型类、泛型委托等和泛型办法声明相似:
//泛型类publicclassGenericClasswhereT:ISports
{
}//泛型接口publicinterfaceGenericInterface{
}//方形委托publicdelegatevoidDo()whereT:ISports;
WebServiceWCF都不能用泛型,为什么?
由于这些是跨言语的,其他言语也能用,不支撑泛型,服务在发布的时分是有必要确认的,泛型在编译时确认不了。
3、泛型束缚
没有束缚,其实很瘦限制。
基类束缚:
whereT:BaseModel
1、能够把T当成基类—权力
2、T有必要是BaseModel或许其子类
为什么要有束缚?
由于有束缚才有权力,自由主义的开山祖师洛克先生说过,有了法令,才有自由。
泛型:不同的类型都能进来,任何的乐行都能过来,你知道我是谁?
whereT:class引证类型束缚;引证类型
whereT:struct
whereT:new()无参够赞函数束缚
publicstaticvoidShow(TtParameter)//whereT:String//密封类束缚的不行,由于没有意义//whereT:People//whereT:ISportswhereT:People,ISports,IWork,new()
{
Console.WriteLine(“Thisis{0},parameter={1},type={2}”,typeof(GenericConstraint),tParameter.GetType().Name,tParameter);
Console.WriteLine($”{tParameter.Id}{tParameter.Name}”);
tParameter.Hi();//tParameter.Pingpang();}
publicTGetT()//whereT:class//引证类型束缚//whereT:struct//值类型whereT:new()//无参数构造函数whereS:class{//returnnull;//returndefault(T);//default是个关键字,会根据T的类型去获得一个默认值returnnewT();//thrownewException();}
4、协变、逆变
.net4.0才呈现的,只能放在接口或许委托的泛型参数前面
out协变covariant,润饰返回值,只能组我诶返回值
in逆变contravariant,润饰传输参数,只能作为传入值
publicclassBird
{publicintId{get;set;}
}publicclassSparrow:Bird
{publicstringName{get;set;}
}
{//协变IEnumerablebirdList1=newList();
IEnumerablebirdList2=newList();
Funcfunc=newFunc(()=>null);
ICustomerListOutcustomerList1=newCustomerListOut();
ICustomerListOutcustomerList2=newCustomerListOut();
}
{//逆变ICustomerListIncustomerList2=newCustomerListIn();
ICustomerListIncustomerList1=newCustomerListIn();
ICustomerListInbirdList1=newCustomerListIn();
birdList1.Show(newSparrow());
birdList1.Show(newBird());
Actionact=newAction((Birdi)=>{});
}
{
IMyListmyList1=newMyList();
IMyListmyList2=newMyList();//协变IMyListmyList3=newMyList();//逆变IMyListmyList4=newMyList();//协变+逆变}
5、泛型缓存
每个不同的T,都会生成一份不同的副本,合适不同的类型,需要缓存一份数据场景,效率高

未经允许不得转载:IT技术网站 » C#泛型
分享到: 更多 (0)

评论 抢沙发

评论前必须登录!

 

志在指尖 用双手敲打未来

登录/注册IT技术大全

热门IT技术

C#基础入门   SQL server数据库   系统SEO学习教程   WordPress小技巧   WordPress插件   脚本与源码下载