C# 中的泛型方法是什么?
csharpprogrammingserver side programming更新于 2025/10/14 16:22:17
泛型允许您编写可处理任何数据类型的类或方法。声明一个带有类型参数 − 的泛型方法。
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("Int values before calling swap:");
Console.WriteLine("a = {0}, b = {1}", a, b);
Console.WriteLine("Char values before calling swap:");
Console.WriteLine("c = {0}, d = {1}", c, d);
Swap(ref a, ref b);
Swap(ref c, ref d);
Console.WriteLine("Int values after calling swap:");
Console.WriteLine("a = {0}, b = {1}", a, b);
Console.WriteLine("Char values after calling swap:");
Console.WriteLine("c = {0}, d = {1}", c, d);
Console.ReadKey();
}
}
}
输出
Int values before calling swap: a = 45, b = 60 Char values before calling swap: c = K, d = P Int values after calling swap: a = 60, b = 45 Char values after calling swap: c = P, d = K

