在C#中,
例如:
where T : class
是什么意思?例如:
public IList<T> DoThis<T>() where T : class
简单来说,这是将泛型参数限制为一个类(或更具体地说,是一个引用类型,可以是类、接口、委托或数组类型)。
有关详细信息,请参见MSDN文章。
这是对 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 T : class, IComparable, new()
。 - Izzy这限制了T
只能是引用类型。你不能把值类型(struct
和原始类型,除了string
)放在那里。
where T: class
的字面意思是 T 必须是一个类
。它可以是任何引用类型。现在,每当任何代码调用你的 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
}
where T : class
时无法使用 new T()
。你需要指定 where T : new()
才能允许使用它。 - esskar这意味着在使用泛型方法时,作为T
使用的类型必须是一个类 - 也就是说它不能是一个结构体或内置数字类型,如int
或double
// Valid:
var myStringList = DoThis<string>();
// Invalid - compile error
var myIntList = DoThis<int>();
T代表一个对象类型,它意味着你可以给任何类型的对象。
IList:如果IList s=new IList;现在s.add("Always accept string.")。
这里的 T 指的是一个类,它可以是引用类型。
'T'代表泛型类型。这意味着它可以接受任何类型的类。以下文章可能会有所帮助:
'http://www.15seconds.com/issue/031024.htm