难以理解“泛型”的例子

时间:2010-12-09 01:15:05

标签: c# generics

我正在阅读一本试图用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();
  }
}

令我困惑的是Print方法的参数。我理解在处理诸如List<T>之类的集合时使用泛型类型占位符。但是我不明白的是<T>如何使用方法?代码只是说传递给Print()方法的参数类型在设计时才知道,可能是什么?有人可以帮我解读一下吗?谢谢。

4 个答案:

答案 0 :(得分:5)

通过使用泛型类型声明方法,可以使方法更加灵活,因为它可以处理您选择的任何类型的变量,包括基本类型(当然,除非您指定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);

答案 1 :(得分:3)

你写的正是这样。在方法级别也可以使用通用参数。它们的行为与类级别完全相同,只是类型参数的范围仅限于方法。

答案 2 :(得分:3)

  

代码是否只是说传递给Print()方法的参数类型在设计时才知道,可能是什么?

这正是它所说的。现在,每当编译器找到对T的引用时,它将自动替换实例或方法调用中指定的类型(如果该方法是通用的)。这种方法的一个主要例子是我多次使用(并且已经使用过)的模式。它基本上是从一种类型到另一种类型的安全演员。您要强制转换的类型被指定为通用参数。例如:

var something = SafeCast<int>("123.434"); // something == 123
var somethingElse = SafeCast<int>(23.45f); // somethingElse == 23
var somethingNull = SafeCast<int>(null);  // this shouldn't throw but return a null

答案 3 :(得分:0)

由于编译器不知道T是什么,并且T没有在类级别定义,因此编译器需要知道将参数转换为什么,这就是参数发挥作用的地方;)

相关问题