您的位置:首页 > 编程语言 > ASP

泛型总结

2016-04-10 22:56 537 查看


/// 泛型是包含类型参数的一种类型

/// 泛型,实质是为了避免大量重构而将传入参数类型作为变量进行传递来实现重构的效果

/// 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

{

}

/[b]*********************************************************[/b]/

解决方案图示————————>>

///


类: people man bird superman


接口: iflyable


man 继承 people类

superman 继承 man类

bird superman 实现 iflyable接口

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  泛型 C# ASP-NET