static void Swap<T>(ref T lhs, ref T rhs) //當指定為int時此行類似 static void Swap<int>(ref int lhs,ref int rhs)
{
 T temp; //此時的T 也是int型態,類似 int temp;
 temp = lhs;
 lhs = rhs;
 rhs = temp;
}
public static void TestSwap()
{
    int a = 1;
    int b = 2;
    Swap<int>(ref a, ref b);  //在此時會將 T 指定為int型態
    MessageBox.Show("a="+a + ",b=" + b,"呈現結果");
}

呈現結果

泛型方法

Leave a Comment