3

非泛型委托声明如下:

delegate void Print(int arg);

wherevoid返回类型int参数类型

通用委托声明如下:

delegate void Print<T> (T arg);

wherevoid又是返回类型,T括号中是泛型参数类型

现在我们已经知道了返回类型和参数类型,那么为什么我们需要额外的类型在尖括号中Print<T>呢?它意味着什么?

谢谢大家。

4

4 回答 4

6

<T>需要in告诉编译器Print<T>您打算创建一个泛型方法。否则它可能会认为T是某种类型,而不是类型参数。虽然您可以直观地推断出作者的意思,但编译器对它更字面化。

于 2012-08-22T05:15:51.713 回答
4

它告诉编译器他正在处理一个泛型方法。

您的建议是编译器将推断此声明是通用的:

delegate void Print (T arg)

在存在的情况下会发生什么

class T { }

?

于 2012-08-22T05:16:11.997 回答
4

如果括号中没有那个“额外类型”,C# 编译器就无法知道它是否应该T在参数列表中将其视为泛型类型,或者它应该期望一个名称实际上T与 in 相同的类型class T {}

于 2012-08-22T05:17:23.960 回答
2

附带说明:delegate void Print(T arg);在泛型类中是完全有效的语法,它意味着“这个委托与整个类采用相同的类型arg”(假设 T 是该类的泛型类型)。

您也可以delegate void Print2<T>(T arg);在同一个类中声明。含义(编译器警告您)是不同的:委托使用任何类型作为参数,并且与类T中使用的类型无关T(请注意,在您的代码中这样做是不好且令人困惑的想法)。

class GenericClass<T>
{
   delegate void Print(T arg); // T is the same as T in the class

   delegate void Print2<T>(T arg); // T is unrelated to T in the class.
}

具有功能的类似代码:

using System;
class Program {
void Main()
{
  var x = new A<int>();
  // x.Print("abc");  - compile time error
  x.Print(1); // Print only accepts same Int32 type 

  x.Print2(1);     // Print2 can use as the same Int32 used for class
  x.Print2("abc"); // as well any other type like string.
}

public class A<T>
{
   public void Print(T arg)
   {
      Console.WriteLine("Print:{0} = {1}", arg.GetType().FullName, arg);
   }
   public void Print2<T>(T arg)
   {
Console.WriteLine("PRINT2:{0} = {1}", arg.GetType().FullName, arg);
   }
}
}
于 2012-08-22T06:16:51.427 回答