急,求解面试题(交换两个变量)题目:
在.net2.0 中写一个通用的方法Swit(),可任一交换两个变量。
要求:1.两变量为同类型的任一类型变量 2.没有装拆箱操作

解决方案 »

  1.   

    class Helper<T>
    {
      public static void swap(ref T t1, ref T t2)
      {
         T temp = t1;
         t1 = t2;
         t2 = temp;
      }
    }
      

  2.   

    这样算不?
    private void Swit<T>(ref T a, ref T b)
    {
        T t = a;
        a = b;
        b = t;
    }private void button1_Click(object sender, EventArgs e)
    {
        int a = 1;
        int b = 2;
        Swit<int>(ref a, ref b);
        Console.WriteLine("a={0},b={1}", a, b);
    }
      

  3.   

    public void swap(int a,int b)
    {
    a=b+(b=a)*0
    }
      

  4.   

    public void swap(int a,int b)
    {
    a=b+(b=a)*0;
    }hehe 忘了;
      

  5.   


    using System;
    using System.Collections;
    using System.Collections.Generic;/// <summary>
    /// Switch范型类
    /// </summary>
    public class Switch<E>
    {
    public Switch()
    {

    }
        /// <summary>
        /// 实现交换
        /// </summary>
        /// <param name="e"></param>
        /// <param name="t"></param>
        public void Exchange(ref E e, ref E t)
        {
            E temp = e;
            e = t;
            t = e;
        }
    }
      

  6.   

    利用.net编译原理,没用到装箱拆箱和临时变量
      

  7.   

    public static void Swit<T>(ref T a, ref T b)
    {
        T tmp = a;
        a = b;
        b = tmp;
    }顺便问一句: a=b+(b=a)*0; 即使用是int型的变数,这个行吗?
      

  8.   

    public static void Swit<T>(ref T a, ref T b)
    {
        T tmp = a;
        a = b;
        b = tmp;
    }顺便问一句: a=b+(b=a)*0; 即使用是int型的变数,这个行吗?
      

  9.   

    泛型还好。实在不行判断一下type。然后根据不同的type进行转换吧。