2010-09-24 72 views

回答

83

简单地讲,这是约束通用参数传递给一个类(或者更具体地说是一个可以是类,接口,委托或数组类型的引用类型)。

有关详细信息,请参阅此MSDN article

+2

您错过了一个案例。 T的类型参数也可以是任何其他被约束为引用类型的类型参数。 – 2010-09-24 15:23:25

+0

Upvoted为所提供的MSDN链接。它非常有用 – SaddamBinSyed 2017-09-13 08:32:07

1

'T'表示泛型类型。这意味着它可以接受任何类型的课程。以下文章可能有所帮助:

http://www.15seconds.com/issue/031024.htm 
34

这是一个generic type constraint。在这种情况下,这意味着泛型T必须是引用类型(类,接口,委托或数组类型)。

8

这意味着所使用的类型如T时的一般方法,使用必须是类 - 即,它不能是一个结构或内置在数字像intdouble

// Valid: 
var myStringList = DoThis<string>(); 
// Invalid - compile error 
var myIntList = DoThis<int>(); 
28

这是一个类型约束T,指定它必须是一个类。

where子句可用于指定其他类型的限制,例如:

where T : struct // T must be a struct 
where T : new() // T must have a default parameterless constructor 
where T : IComparable // T must implement the IComparable interface 

欲了解更多信息,请查看MSDN页面上的where clause,或generic parameter constraints

+3

可以将它们组合在一起,例如:'where T:class,IComparable,new()' – Izzy 2016-03-10 09:49:44

13

这限制了T参考类型。您将无法将值类型(struct s和基本类型除string)放在那里。

4

T代表的对象类型,它意味着你可以给任何类型的。 IList:如果IList =新IList; 现在s.add(“总是接受字符串。”)。

5

where T: class的原意是指T has to be a class。它可以是任何参考类型。现在,只要有任何代码调用您的DoThis<T>()方法,它必须提供一个类来取代T。例如,如果我是叫你DoThis<T>()方法那么我将不得不调用它像以下:

DoThis<MyClass>(); 

如果您metthod就像是这样的:

public IList<T> DoThis<T>() where T : class 
{ 
    T variablename = new T(); 

    // other uses of T as a type 

} 

然后在以往任何时候牛逼出现在方法,它将被MyClass取代。这样编译器调用,将类似于下面的最后一个方法:

public IList<MyClass> DoThis<MyClass>() 
{ 
    MyClass variablename= new MyClass(); 

    //other uses of MyClass as a type 

    // all occurences of T will similarly be replace by MyClass 
} 
+3

-1:'new T()'不可能和'where T:class'一起使用。你必须指定'where T:new()'来允许它做。 – esskar 2013-01-22 18:02:39

+0

@explorer我们可以定义一个单一的泛型方法,并从多个地方调用它来通过从不同地方传入不同参数来插入记录。 – User 2015-06-18 06:47:48

2

这里t代表一个Class.It可以是引用类型。