C#.Net 泛用型別(generic萬用型別)範例 , 來源: 資策會 講師 王芳芳指導
///
/// 把型別當參數傳, 呼叫時傳入 則, 傳入參數的型別為int, 如: SwapAnyType (ref a, ref b)
///
/// 傳入型別
/// 傳入參數a
/// 傳入參數b
void SwapAnyType (ref T a, ref T b)
{
T temp;
temp = b;
b = a;
a = temp;
}
private void button7_Click(object sender, EventArgs e)
{
int a, b;
a = 100;
b = 200;
MessageBox.Show(a + ", " + b);
SwapAnyType (ref a, ref b);
//SwapAnyType(ref a, ref b); //也可以這樣用, 程式會跟據a,b的型別去推斷傳進來的型別
MessageBox.Show(a + ", " + b);
}
或
private void button1_Click(object sender, EventArgs e)
{
//C# 1.0 Collection
System.Collections.ArrayList list1 = new System.Collections.ArrayList();
list1.Add(new Point(1, 1));
list1.Add(new Point(2, 2));
//.......
MessageBox.Show(((Point)list1[0]).X + ", " + ((Point)list1[0]).Y); //需轉型
//C# 2.0 Generic class Collection
System.Collections.Generic.List list2 = new List (); //new一個泛用型別的coleection
list2.Add(new Point(1, 1));
list2.Add(new Point(2, 2));
//........
MessageBox.Show(list2[0].X + ", " + list2[0].Y);//不需轉型
}
沒有留言:
張貼留言