泛型允许您编写可与任何数据类型一起使用的类或方法。使用类型参数声明泛型方法-
static void Swap(ref T lhs, ref T rhs) {}
要调用上面显示的泛型方法,这是一个示例-
Swap(ref a, ref b);
让我们看看如何在C#中创建泛型方法-
using System; using System.Collections.Generic; namespace Demo { class Program { static void Swap(ref T lhs, ref T rhs) { T temp; temp = lhs; lhs = rhs; rhs = temp; } static void Main(string[] args) { int a, b; char c, d; a = 45; b = 60; c = 'K'; d = 'P'; Console.WriteLine("调用swap之前的Int值:"); Console.WriteLine("a = {0}, b = {1}", a, b); Console.WriteLine("调用swap之前的Char值:"); Console.WriteLine("c = {0}, d = {1}", c, d); Swap(ref a, ref b); Swap(ref c, ref d); Console.WriteLine("调用swap之后的Int值:"); Console.WriteLine("a = {0}, b = {1}", a, b); Console.WriteLine("调用swap之后的Char值:"); Console.WriteLine("c = {0}, d = {1}", c, d); Console.ReadKey(); } } }
输出结果
调用swap之前的Int值: a = 45, b = 60 调用swap之前的Char值: c = K, d = P 调用swap之后的Int值: a = 60, b = 45 调用swap之后的Char值: c = P, d = K