泛型学习(三)
5 泛型与继承
开放类型:含有类型参数的类型,“开放”即为 数据类型不确定。
(包括:类型参数本身,包含开放类型的构造类型,元素类型为开放类型的数组类型)
封闭类型:开放类型以外的类型 (即没有泛型类型的值类型 引用类型)
* 基本原则: 开放类型不能从封闭类型中继承。
5.1 普通类型与派生泛型类
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApp { class GenericInheritSample { public static void Main() { CzIndexedAssemble<Contact> asm = new CzIndexedAssemble<Contact>(5); asm[0] = new Contact("赵丽"); asm[1] = new Business("Mike"); asm[2] = new Business("李明"); asm[3] = new Business("Tom"); asm[4] = new Family("王小强"); asm.Sort(); for (int i = 0; i < 5; i++) asm[i].Output(); Console .WriteLine ("---------------------------") asm.Output (); Console .ReadLine (); } } //泛型类:索引集合CzIndexedAssemble public class CzIndexedAssemble<T> : czrelation<int, T> where T : IComparable { public T this[int index] { get { return Right[index]; } set { Right[index] = value; } } public CzIndexedAssemble(int iLength) : base(iLength) { for (int i = 0; i < Length; i++) Left[i] = i; } public void Output() { T t; for (int i = 0; i < Length; i++) { t = Right[Left[i]]; if (t != null) { IOutput io = t as IOutput; if (io != null) io.Output(); else Console.WriteLine(t); } } } public void Sort() { int tmp; for (int i = Length; i > 0; i--) { for (int j = 0; j < i - 1; j++) { if (Right[Left[j]].CompareTo(Right[Left[j + 1]]) > 0) { tmp = Left[j + 1]; Left[j + 1] = Left[j]; Left[j] = tmp; } } } } } }