【发布时间】:2010-09-24 11:55:16
【问题描述】:
在 C# 中,where T : class 是什么意思?
即。
public IList<T> DoThis<T>() where T : class
【问题讨论】:
在 C# 中,where T : class 是什么意思?
即。
public IList<T> DoThis<T>() where T : class
【问题讨论】:
简单地说,这是将泛型参数约束到一个类(或者更具体地说,一个引用类型,可以是类、接口、委托或数组类型)。
查看MSDN article了解更多详情。
【讨论】:
这是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
有关更多信息,请查看 where clause 或 generic parameter constraints 上的 MSDN 页面。
【讨论】:
where T : class, IComparable, new()
must be a class?接口呢?如果解释了class这个词的含义,就可以掌握这个概念。或者,这是一个缺陷。
这是一个generic type constraint。在这种情况下,这意味着泛型类型T 必须是引用类型(类、接口、委托或数组类型)。
【讨论】:
这将T 限制为引用类型。您将无法在其中放置值类型(structs 和基本类型,string 除外)。
【讨论】:
这意味着当使用泛型方法时,用作T的类型必须是一个类——即它不能是一个结构体或像int或double这样的内置数字
// Valid:
var myStringList = DoThis<string>();
// Invalid - compile error
var myIntList = DoThis<int>();
【讨论】:
where T: class 字面意思是 T has to be a class。它可以是任何引用类型。现在,每当任何代码调用您的DoThis<T>() 方法时,它都必须提供一个类来替换T。例如,如果我要调用你的 DoThis<T>() 方法,那么我将不得不像下面这样调用它:
DoThis<MyClass>();
如果你的方法是这样的:
public IList<T> DoThis<T>() where T : class
{
T variablename = new T();
// other uses of T as a type
}
然后,无论 T 出现在您的方法中的何处,它都会被 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
}
【讨论】:
new T() 不能与 where T : class 一起使用。你必须指定where T: new() 才能被允许这样做。
称为类型参数约束。它实际上限制了 T 可以是什么类型。
类型参数必须是引用 类型;这也适用于任何类别, 接口、委托或数组类型。
【讨论】:
T代表一个对象类型,它暗示你可以给出任何类型。 IList : 如果 IList s=new IList; 现在 s.add("总是接受字符串。")。
【讨论】:
这里的T指的是一个类。它可以是一个引用类型。
【讨论】:
'T' 表示泛型类型。这意味着它可以接受任何类型的类。以下文章可能会有所帮助:
http://www.15seconds.com/issue/031024.htm
【讨论】: