用泛型取代直接宣告型別的好處

2012041016:46

        //定義泛型方法,<T>的 T 是型別參數,起暫訂型別的作用,編譯時被真正型別取代。
        public static void Swap<T>(ref T lhs, ref T rhs)
        {
            //示範將左右內容對調
            T temp;
            temp = lhs;
            lhs = rhs;
            rhs = temp;
        }

        //使用泛型方法
        public static void TestSwap()
        {
            //宣告 T 為 int 型別
            int a = 1, b = 3;
            Swap<int>(ref a, ref b);

            //宣告 T 為 string 型別
            string s1 = "Hello", s2 = "world";
            Swap<string>(ref s1, ref s2);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            TestSwap();
        }