C#泛型用法实例分析
本文实例分析了C#泛型用法。分享给大家供大家参考。具体分析如下:
这里演示如何创建具有单个类型参数的自定义泛型列表类,以及如何实现IEnumerable<T>以便对列表的内容启用foreach迭代。此示例还演示客户端代码如何通过指定类型参数来创建该类的实例,以及该类型参数的约束如何实现对类型参数执行其他操作。
usingSystem;
usingSystem.Collections;
usingSystem.Collections.Generic;
usingSystem.Text;
namespaceGenerics_CSharp
{
//尖括号中的类型参数T。
publicclassMyList<T>:IEnumerable<T>
{
protectedNodehead;
protectedNodecurrent=null;
//嵌套类型也是T上的泛型
protectedclassNode
{
publicNodenext;
//T作为私有成员数据类型。
privateTdata;
//在非泛型构造函数中使用的T。
publicNode(Tt)
{
next=null;
data=t;
}
publicNodeNext
{
get{returnnext;}
set{next=value;}
}
//T作为属性的返回类型。
publicTData
{
get{returndata;}
set{data=value;}
}
}
publicMyList()
{
head=null;
}
//T作为方法参数类型。
publicvoidAddHead(Tt)
{
Noden=newNode(t);
n.Next=head;
head=n;
}
//实现GetEnumerator以返回IEnumerator<T>,从而启用列表的
//foreach迭代。请注意,在C#2.0中,
//不需要实现Current和MoveNext。
//编译器将创建实现IEnumerator<T>的类。
publicIEnumerator<T>GetEnumerator()
{
Nodecurrent=head;
while(current!=null)
{
yieldreturncurrent.Data;
current=current.Next;
}
}
//必须实现此方法,因为
//IEnumerable<T>继承IEnumerable
IEnumeratorIEnumerable.GetEnumerator()
{
returnGetEnumerator();
}
}
publicclassSortedList<T>:MyList<T>whereT:IComparable<T>
{
//一个未优化的简单排序算法,
//该算法从低到高对列表元素排序:
publicvoidBubbleSort()
{
if(null==head||null==head.Next)
return;
boolswapped;
do
{
Nodeprevious=null;
Nodecurrent=head;
swapped=false;
while(current.next!=null)
{
//由于需要调用此方法,因此,SortedList
//类在IEnumerable<T>上是受约束的
if(current.Data.CompareTo(current.next.Data)>0)
{
Nodetmp=current.next;
current.next=current.next.next;
tmp.next=current;
if(previous==null)
{
head=tmp;
}
else
{
previous.next=tmp;
}
previous=tmp;
swapped=true;
}
else
{
previous=current;
current=current.next;
}
}//endwhile
}while(swapped);
}
}
//一个将自身作为类型参数来实现IComparable<T>的简单类,
//是对象中的
//常用设计模式,这些对象
//存储在泛型列表中。
publicclassPerson:IComparable<Person>
{
stringname;
intage;
publicPerson(strings,inti)
{
name=s;
age=i;
}
//这会使列表元素
//按age值排序。
publicintCompareTo(Personp)
{
returnage-p.age;
}
publicoverridestringToString()
{
returnname+":"+age;
}
//必须实现Equals。
publicboolEquals(Personp)
{
return(this.age==p.age);
}
}
classGenerics
{
staticvoidMain(string[]args)
{
//声明并实例化一个新的范型SortedList类。
//Person是类型参数。
SortedList<Person>list=newSortedList<Person>();
//创建name和age值以初始化Person对象。
string[]names=newstring[]{"Franscoise","Bill","Li","Sandra","Gunnar","Alok","Hiroyuki","Maria","Alessandro","Raul"};
int[]ages=newint[]{45,19,28,23,18,9,108,72,30,35};
//填充列表。
for(intx=0;x<names.Length;x++)
{
list.AddHead(newPerson(names[x],ages[x]));
}
Console.WriteLine("UnsortedList:");
//打印出未排序的列表。
foreach(Personpinlist)
{
Console.WriteLine(p.ToString());
}
//对列表进行排序。
list.BubbleSort();
Console.WriteLine(String.Format("{0}SortedList:",Environment.NewLine));
//打印出排序的列表。
foreach(Personpinlist)
{
Console.WriteLine(p.ToString());
}
Console.WriteLine("Done");
}
}
}
希望本文所述对大家的C#程序设计有所帮助。