第2章(五) 数据类型与流程控制.pptVIP

  • 2
  • 0
  • 约1.54万字
  • 约 46页
  • 2018-06-06 发布于河北
  • 举报
第2章(五) 数据类型与流程控制

【例3-8】泛型的定义与使用。 using System; using System.Collections.Generic; using System.Collections; using System.Text; namespace ConsoleApplication2{ class StackT:CollectionBase{ private T[] store; private int size; public Stack(){ store = new T[10]; size = 0; } public void Push(T x){ store[size++] = x; } public T Pop(){ return store[--size]; } } } namespace ConsoleApplication2{ class Program{ [STAThread] static void Main(string[] args){ Stackstring stack = new Stackstring(); stack.Push(ni hao); stack.Push(wo buhao); Console.WriteLine(stack.Pop()); Console.WriteLine(stack.Pop()); Console.Read(); } } } 可空泛型 可空类型是泛型结构NullableT的实例。 例如,NullableInt32读作“可以为null的Int32”,可以将其赋值为任一个32位整数值,也可以将其赋值为null值。 可空类型具有以下特性: (1)可空类型表示可被赋值为null值的值类型变量。但是要注意,由于引用类型已支持null值,因此不能用该类型创建基于引用类型的null类型。 (2)语法“T?”是泛型“NullableT”的简写,此处的T为值类型。这两种形式可以互换。如Nullableint也可以写为int?。 (3)程序员可以使用泛型的HasValue和Value只读属性测试是否为空和检索值,如果此变量包含值,则HasValue属性返回True;如果此变量的值为空,则返回False。 2.4.5 泛型集合 在System.Collections.Generic命名空间下,提供了常用的泛型集合类。 泛型集合类 非泛型集合类 泛型集合用法举例 ListT ArrayList Liststring dinosaurs = new Liststring( ); DictionaryTKey,Tvalue Hashtable Dictionarystring, string d = new Dictionarystring, string( ); d.Add (txt, notepad.exe); QueueT Queue Queuestring q = new Queuestring( ); q.Enqueue(one); StackT Stack Stackstring s = new Stackstring( ); s.Push(one); s.Pop( ); SortedListTKey,TValue SortedList SortedListstring, string list = new SortedListstring, string( ); list.Add (txt, notepad.exe); list.TryGetValue(tif, out value)) 哈希集合 HashSet HashSetT泛型类提供了高性能的数学集合运算,一个HashSetT对象的容量是指该对象可以容纳的元素个数。 常用方法: UnionWith方法:并集或Set加法 IntersectWith方法:交叉 ExceptWith方法:set减法 SymmetricExceptWith方法:余集 列表和排序列表 ListT泛型类表示可通过索引访问的强类型对象列表,该类提供了对列表进行搜索、排序和操作的方法。 常用方法如下: Add方法:将指定值的元素添加到列表中。 Insert方法:在列表的中间插入一个新元素。 Conta

文档评论(0)

1亿VIP精品文档

相关文档