当前位置: 移动技术网 > IT编程>开发语言>.net > C#-泛型类型

C#-泛型类型

2018年11月21日  | 移动技术网IT编程  | 我要评论

最新军情观察室,美国政治避难,谏山实生

概述
  泛型类和泛型方法兼具可重用性、类型安全性和效率,这是非泛型类和非泛型方法无法实现的
  泛型通常与集合以及作用于集合的方法一起使用
   泛型所属命名空间:system.collections.generic 
  可以创建自定义泛型接口、泛型类、泛型方法、泛型事件和泛型委托,以提供自己的通用解决方案,设计类型安全的高效模式
  泛型允许编写一个可以与任何数据类型一起工作的类或方法
 
示例
 
 1 using system;
 2 using system.collections.generic;
 3 
 4 namespace generictest
 5 {
 6     public class testgeneric<t>
 7     {
 8         
 9         private t[] array;
10         public testgeneric(int i)
11         {
12             array = new t[i + 1];
13         }
14         public t getitem(int index)
15         {
16             return array[index];
17         }
18         public void setitem(int index, t value)
19         {
20             array[index] = value;
21         }
22     }
23 
24     class tester
25     {
26         static void main(string[] args)
27         {
28             testgeneric<char> myarray = new testgeneric<char>(5);
29             for (int i = 0; i < 5; i++)
30             {
31                 myarray.setitem(i, (char)(i + 97));
32             }
33 
34             for (int i=0; i<5; i++)
35             {
36                 console.writeline(myarray.getitem(i));
37             }
38             console.writeline();
39             console.readkey();
40         }
41 
42     }
43 }

 

结果

 

约束

  对代码能够在实例化类时用于类型参数的类型种类施加限制
  约束的方式是指定t的祖先,即继承的接口或类
  代码尝试使用某个约束所不允许的类型来实例化类,则会产生编译时错误
  定义:public t getinfo<t>(string id) where t : cbaseinfo
 

约束限定条件

  •  t:struct    类型参数必须是值类型。可以指定除 nullable 以外的任何值类型
  •  t:class      类型参数必须是引用类型,包括任何类、接口、委托或数组类型
  •  t:new()      类型参数必须具有无参数的公共构造函数。当与其他约束一起使用时new() 约束必须最后指定
  •  t:<基类名> 类型参数必须是指定的基类或派生自指定的基类
  •  t:<接口名称> 类型参数必须是指定的接口或实现指定的接口。可以指定多个接口约束。约束接口也可以是泛型的。
  •  t:u    为 t 提供的类型参数必须是为 u 提供的参数或派生自为 u 提供的参数,称为裸类型约束

例:

public class myarray<t> : b<t> where t : new() { }

定义多个类型参数和约束:

public class base<a,b,c> where a: struct
where b: new()
where c: class
{ }

泛型也可以继承泛型:

class d:c<string,int>

class e<u,v>:c<u,v>

class f<u,v>:c<string,int>

 

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网