c#使用泛型方法交换两个数据的值

使用泛型方法交换int型值和char类型值

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp9
{
    class Program
    {
        static void Swap<T>(ref T x,ref T y)  //定义Swap泛型方法,将参数定义为泛型
                                              //ref关键字,使用引用进行传值
        {
            T temp;
            temp = x;
            x = y;
            y = temp;
        }
        static void Main(string[] args)
        {
            int a = 1;
            int b = 2;  //用于交换整型数据

            char c = 'C';
            char d = 'D';   //用于交换字符数据

            Console.WriteLine("交换前的int型数据为: " + a + " " + b);
            Swap<int>(ref a, ref b);//ref关键字,使用引用进行传值
            Console.WriteLine("交换后的Int型数据为: " + a + " " + b);

            Console.WriteLine("交换前的char型数据为: " + c + " " + d);
            Swap<char>(ref c, ref d);//ref关键字,使用引用进行传值
            Console.WriteLine("交换后的char型数据为: " + c + " " + d);
        }
    }
}

运行结果为:


输出.PNG
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容