泛型的定義
泛型,就是創建使用通用類型的類或方法。泛型
旨在改進如下方面:
二進制代碼的重用。
性能(不需要裝箱和拆箱)。
易於閱讀。
類型安全。
System.Collections.Generics命名空間中,包含大
量類和接口,其中的接口也都模擬了System.
Collections命名空間下相應的非泛型類型。如:
ICollection<T>
IComparer<T>
IDictionary<TKey,TValue>
IEnumerable<T>
IEnumerator<T>
IList<T>
定義一個泛型方法
public void Swap<T>(ref T a, ref T b)
{
T temp;
temp = a;
a = b;
b = temp;
}
一個泛型方法是在方法名稱後、參數列表前定義
類型參數的。上面的方法中,可以操作任意兩個
<T>類型的參數。
定義一個泛型類
public class Point<T>{
private T xPos;
private T yPos;
public Point(T x, T y) {
xPos = x;
yPos = y;
}
public T X{
get { return xPos; }
set { this.xPos = value; }
}
泛型類的定義
public class Point<T>
{
public Point()
{
//
//TODO: 在此處添加構造函數邏輯
//
}
private T xPos;
private T yPos;
public T X
{
get { return this.xPos; }
set { this.xPos = value; }
}
public T Y
{
get { return this.yPos; }
set { this.yPos = value; }
}
public override string ToString()
{
return string.Format("X:{0},Y{1}",xPos,yPos);
}
public Point(T x,T y)
{
xPos = x;
yPos = y;
}
}
///// Point<int> p = new Point<int>(10, 20);
Response.Write(p.ToString());
Point<float> pf = new Point<float>(12.2f, 23.2f);
Response.Write(pf.ToString());