“哪里T:somevalue”是什么意思?

时间:2009-03-07 18:29:13

标签: c# generics constraints

where T : somevalue是什么意思?我刚看到一些代码where T : Attribute。我认为这与泛型有关,但我不确定这意味着什么或它在做什么。

有人知道吗?

4 个答案:

答案 0 :(得分:28)

它是constraint on a type parameter,意味着赋予通用类或方法的类型T必须从类Attribute继承

例如:

public class Foo<T> : 
   where T : Attribute
{
    public string GetTypeId(T attr) { return attr.TypeId.ToString(); }
 // ..
}

Foo<DescriptionAttribute> bar; // OK, DescriptionAttribute inherits Attribute
Foo<int> baz; // Compiler error, int does not inherit Attribute

这很有用,因为它允许泛型类使用T类型的对象执行操作,并且知道任何T的内容也必须是Attribute

在上面的示例中,GetTypeId可以查询TypeId的{​​{1}},因为attrTypeId的属性,因为{ {1}}是Attribute,它必须是继承自attr的类型。

约束也可用于泛型方法,效果相同:

T

您可以对类型进行其他限制;来自MSDN

  

Attribute

     

type参数必须是值   类型。除Nullable外的任何值类型   可以指定。

     

public static void GetTypeId<T>(T attr) where T : Attribute { return attr.TypeId.ToString(); }

     

type参数必须是引用   类型;这也适用于任何类,   接口,委托或数组类型。

     

where T: struct

     

type参数必须是public   无参数构造函数。使用时   连同其他约束,   必须指定new()约束   最后。

     

where T : class

     

必须是或派生类型参数   来自指定的基类。

     

where T : new()

     

type参数必须是或实现的   指定的接口。多   接口约束可以   指定。约束界面   也可以是通用的。

     

where T : <base class name>

     

为T提供的类型参数必须   是或来自论证   供给U.这称为裸体   类型约束。

答案 1 :(得分:5)

另外,其他人说,你也有以下内容:

  • new() - T必须具有默认构造函数
  • class - T必须是引用类型
  • struct - T必须是值类型

答案 2 :(得分:1)

where子句用于限制使用泛型时可以传递的参数。在创建泛型类时,根据您计划在类中使用T的方式指定参数类型可能符合您的最佳利益。除了System.Object可以做的任何事情之外,最好使用constraint,因为你会得到编译时错误和运行时。

示例

如果您创建了一个类

class Person<T> where T : System.IComparable<T>
{
   //can now use CompareTo
}

您不能将任何未实现IComparable的内容传递给此类。因此,现在可以安全地对传递给Person类的任何东西使用CompareTo。

答案 3 :(得分:1)

这是一种限制用作泛型参数的类型的方法。所以:

where T : SomeType

意味着T必须来自 SomeType 或实现界面 SomeType

相关问题