泛型总结

/// 泛型是包含类型参数的一种类型
/// 泛型,实质是为了避免大量重构而将传入参数类型作为变量进行传递来实现重构的效果
/// 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值