9--12 泛型 笔记

来源:互联网 发布:珍宝岛冲突 知乎 编辑:程序博客网 时间:2024/05/17 04:30

泛型是为了 代码重用,算法重用。
泛型类,泛型接口,泛型方法
泛型方法—本身不是泛型类,只是在调用方法的时候需要指定一下数据类型
自定义泛型
//主程序:
//T就好像一个占位符,对将来应以的类型进行替代。
//Tkey    Tvalue  
List<int> list=new List<int>
List.Add(10);
List.Add(20);
自己定义泛型(整形)
主程序
MyList m1=new MyList()’
Console.writeLine(m1[4]);
Console.readkey();

Class myList
{
int[] arrInt=new int[]{10,20,30,40,50,60,70};}

public int this[int  index]
{get
{return     arrInt[index];}
Set{
arrInt[index]=value;}
}}

定义一个泛型

主程序里

MyList m1=new MyList();
Console.WriteLine(m1[4]);

m1[0]=900
Console.WriteLine(m1[0]);

MyList m2=new MyList();
m2[2]="helloword"
Console.WriteLine(m2[2]);

MyListGeneric<int> numbers=new MyListGeneric<int>(10);
numbers[0]=10;
numbers[1]=20;
numbers[2]=999;
Console.WriteLine(numbers[1]);

MyListGeneric<string> strs=new MyListGeneric<string>();
strs[0]="i";
strs[1]="am";
strs[2]="cry";
Console.WriteLine(strs[1]);

Console.ReadKey();
}
----------------------
//新建类  
class MyList
{
int[] arrInt=new int[]{10,20,30,40,50,60,70};
public int this[int index]//当前类的索引
{
get{return arrInt[intdex];}
srt{arrInt[index]=value;}
}
}
------------------------
class MyList
{
string[] arrInt=new string[10];
public string this[int index]//当前类的索引
{
get{return arrInt[intdex];}
set{arrInt[index]=value;}
}
}

 

 

T:结构              类型参数必须是值类型。可以指定除Nullable以外的任何值类型。

   

T:类                  类型参数必须是引用类型;这一点也适用于任何类、接口、委托或数组类型。

Tnew()             类型参数必须具有无参数的公共构造函数。当与其他约束一起使用时,new()约束必须最后指定。

 

T<基类名>      类型参数必须是指定的基类或派生自指定的基类。

 

T<接口名称>   类型参数必须是指定的接口或实现指定的接口。可以指定多个接口约束。约束接口也可以是泛型的。

 

TU       T提供的类型参数必须是为 U 提供的参数或派生自为 U提供的参数。

 

      今天的课有点乱,搞的我的思绪都乱了,有点崩溃了。。。。。

原创粉丝点击