扣响C#之门笔记

时间:2021-09-12 00:33:06

23.1 泛型的概念

(1)在普通集合中,元素均被看做是object类型,会有以下缺点
(a)赋值时候将类型转为object,使用时候又将object转为对应的类型,在装箱和拆箱时候造成一定性能损失;
(b)任何类型的数据都可以放进集合里面,不利于类型安全检查;

static void Main(string[] args) { Queue q = new Queue(); q.Enqueue(10); q.Enqueue("wo"); // q.Enqueue(1); foreach (int item in q) //字符串无法转为int 类型输出 { Console.WriteLine(item); Console.Read(); }

(2)泛型集合:泛型集合和普通集合功能是一样的,唯一的区别是泛型集合元素的类型不是object类型,,而是我们制定的类型
定义:Queue<T> myque =new Queue<T>();(T为我们可以指定的类型)

//(2)泛型集合:泛型集合和普通集合功能是一样的,唯一的区别是泛型集合元素的类型不是object类型,而是我们制定的类型 //定义:Queue<T> myque =new Queue<T>();(T为我们可以指定的类型) Queue<int> my = new Queue<int>(); my.Enqueue(10); //my.Enqueue("wo"); //error类型错误不符,无法赋值 my.Enqueue(1);

(3)除了可有有泛型集合,还可以定义泛型函数,结构体,委托等,只需在函数名或者集合名后加<T>

class Program { static void Main(string[] args) { } //(3)除了可有有泛型集合,还可以定义泛型函数,结构体,委托等,只需在函数名或者集合名后加<T> public static void swap<T>(ref T a,ref T b) { T c; c = a; a = b; b = a; } } //(4)泛型的定义中还可以含有多个类型参数 public struct mystruce<V,K> { }

23.2 泛型集合类

C#定义和许多常见泛型集合类,在system.collections.generic 空间下

(1)List<T>类  对应非泛型集合ArrayList

//(1)List<T>类 对应非泛型集合ArrayList List<string> basketballplayer = new List<string>(5); basketballplayer.Add("yaoming"); basketballplayer.Add("kobi"); basketballplayer.Add("maidi"); foreach (string item in basketballplayer) { Console.WriteLine(item); } Console.Read();

(2)Stack<T>类 对应非泛型集合 Stack

//(2)Stack<T>类 对应非泛型集合 Stack Stack<int> s=new Stack<int>(); s.Push(1); s.Push(2); s.Push(3); s.Push(4); foreach (var item in s) { Console.WriteLine(item); } Console.Read(); Console.WriteLine("************");

(3)Queue<T>类 对应非泛型集合 Queue

//(3)Queue<T>类 对应非泛型集合 Queue Queue<int> q = new Queue<int>(); q.Enqueue(1); q.Enqueue(2); q.Enqueue(3); foreach (var item in q) { Console.WriteLine(item); } Console.Read();

23.3 泛型的类型约束

(1)在泛型中由于泛型类型T可以是任何类型,在某些情况下(由于无法确定T的类型时候)会有问题,如下:

(2)此处,由于item为T类型,系统无法确定其类型,因此无法确定这个类型是否包含name成员,因此出错
这时候,使用类型约束(关键字 where T :+限制的范围)where T: Aniamal即可将T限制在Aniamal及其子类中,就可以知道T类型,因此就不会出错了

class Program { static void Main(string[] args) { } } //23.3 泛型的类型约束 //(1)在泛型中由于泛型类型T可以是任何类型,在某些情况下(由于无法确定T的类型时候)会有问题,如下: class AnimalFamily<T> //class AnimalFamily<T> where T: Aniamal { public List<T> t=new List<T>(); public void AddList( T item) { t.Add(item); } public void Display() { foreach (var item in t) { Console.WriteLine(item.name); //错误 1 “T”不包含“name”的定义,并且找不到可接受类型为“T”的第一个参数的扩展方法“name”(是否缺少 using 指令或程序集引用?) E:\张开能\C#\code\第二十三章\Test04\Program.cs 27 40 Test04 //(2)此处,由于item为T类型,系统无法确定其类型,因此无法确定这个类型是否包含name成员,因此出错 //这时候,使用类型约束(关键字 where T :+限制的范围)where T: Aniamal即可将T限制在Aniamal及其子类中,就可以知道T类型,因此就不会出错了 } } } class Aniamal { public string name; }