我正在阅读一本试图用C#理解泛型的书,我遇到了一个我不明白的例子.这是示例代码.
using System;
public class Printer
{
public void Print<T>(T argument)
{
Console.WriteLine(argument.ToString());
}
static void Main(string[] arguments)
{
Printer printer = new Printer();
printer.Print<string>("Hello, World");
Console.WriteLine("Done");
Console.ReadKey();
}
}
Run Code Online (Sandbox Code Playgroud)
令我困惑的是Print方法的论点.我理解在处理诸如的集合时使用泛型类型占位符List<T>.但是我不明白的是如何<T>使用方法?代码只是说传递给Print()方法的参数类型在设计时才知道,可能是什么?有人可以帮我解读一下吗?谢谢.
通过使用泛型类型声明方法,可以使方法更加灵活,因为它可以处理您选择的任何类型的变量,包括基本类型(除非您指定where T : class当然).
另一个非常常见的例子更好地说明了泛型方法的一种用法是一种Swap<T>(T, T)方法:
/*
* The ref keywords mean "pass by reference" i.e. modify the variables as they
* were passed into the method.
*
* The <T> in the signature tells the compiler that T is a generic type, in case
* the class itself doesn't already declare T a generic type.
*/
public void Swap<T>(ref T x, ref T y)
{
// Tells the compiler that temp should be of the same type as x and y,
// regardless of what type T may be
T temp = x;
x = y;
y = temp;
}
int x = 3, y = 6;
Swap<int>(ref x, ref y);
Console.WriteLine(x + " " + y);
char a = 'a', b = 'b';
Swap<char>(ref a, ref b);
Console.WriteLine(a + " " + b);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
464 次 |
| 最近记录: |