使用泛型方法交换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