泛型总结

来源:互联网 发布:淘宝如何延期收货 编辑:程序博客网 时间:2024/05/22 13:06

/// 泛型是包含类型参数的一种类型
/// 泛型,实质是为了避免大量重构而将传入参数类型作为变量进行传递来实现重构的效果
/// T 在方法位置进行声明为 泛型方法,在类的位置进行声明为 泛型类,T代表了传入参数的类型
/// 声明方式 ,例 class MyList,
/// 一个泛型类中的方法不一定是泛型方法
/// 泛型方法不一定在泛型类中
/// 泛型的一个应用:可以将返回值类型为 object 的方法,改写为泛型方法,直接在方法内转换数据类型
/// 泛型的好处:
/// 1.在编译的时候,就可以发现类型传入错误,保证了程序的健壮性
/// 在泛型类List中,泛型类型T定义了允许使用的类型
/// 2.避免了装箱拆箱带来的系统性能损耗
///

///
/// 对泛型的约束
/// class FanXingYueShu where T: new() 传入类型必须包含一个空构造函数(构造函数传入参数为空)
/// class FanXingYueShu where T: struct 只能传入值类型变量
/// class FanXingYueShu where T: class 只能传入引用类型变量
/// class FanXingYueShu where T: People 只能传入People(自定义)类型及其派生类
/// class FanXingYueShu where T: Iflyable 只能传入该接口类型,以及实现了该接口的其他类型
///

代码演示:
program.cs
//泛型规范(约束)
FanXingYueShu fx = new FanXingYueShu();//new() static
FanXingYueShu fx = new FanXingYueShu();//struct
FanXingYueShu fx = new FanXingYueShu();//class
FanXingYueShu fx = new FanXingYueShu();//People
FanXingYueShu fx = new FanXingYueShu();//Man:People
FanXingYueShu fx = new FanXingYueShu();//Bird:Iflyable
FanXingYueShu fx = new FanXingYueShu();// SuperMan:Man, Iflyable

FanXingTest.cs
//方法
class FanXingYueShu where T : new() { }
class FanXingYueShu where T : struct { }
class FanXingYueShu where T : class { }
class FanXingYueShu where T : People { }
class FanXingYueShu where T : Iflyable { }
class FanXingYueShu
where T : Man, Iflyable
{
}
/*********************************************************/
解决方案图示————————>>项目图示///

类: people man bird superman

接口: iflyable


man 继承 people类
superman 继承 man类
bird superman 实现 iflyable接口

0 0
原创粉丝点击