9--12 泛型 笔记

本文深入探讨了泛型在C#编程中的应用,包括泛型类、泛型接口和泛型方法的基本概念。通过实例展示了如何在主程序中使用泛型,以及如何自定义泛型来解决特定问题。详细解释了泛型参数的约束条件,并通过代码实例说明了不同类型的泛型使用。最后,总结了泛型在提高代码复用性和灵活性方面的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

泛型是为了 代码重用,算法重用。
泛型类,泛型接口,泛型方法
泛型方法—本身不是泛型类,只是在调用方法的时候需要指定一下数据类型
自定义泛型
//主程序:
//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 提供的参数。

 

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值