C#泛型方法

来源:百度知道 编辑:UC知道 时间:2024/06/07 02:08:07
如何声明一个简单的 泛型方法与使用

泛型方法是使用类型参数声明的方法,如下所示:

public void Swap<T>(ref T lhs, ref T rhs)
{
T temp;
temp = lhs;
lhs = rhs;
rhs = temp;
}

下面的代码示例演示一种使用 int 作为类型参数的方法调用方式:

public void TestSwap()
{
int a = 1;
int b = 2;

Swap<int>(ref a, ref b);
System.Console.WriteLine(a + " " + b);
}