在C#中where T : class
意味着什么?
IE浏览器.
public IList<T> DoThis<T>() where T : class
Run Code Online (Sandbox Code Playgroud)
Don*_*nut 34
它是一个类型约束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
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请查看MSDN关于where
子句的页面或通用参数约束.
这意味着使用T
泛型方法时使用的类型必须是一个类 - 即它不能是结构或内置数字int
或类似或double
// Valid:
var myStringList = DoThis<string>();
// Invalid - compile error
var myIntList = DoThis<int>();
Run Code Online (Sandbox Code Playgroud)
where T: class
字面意思是T has to be a class
.它可以是任何引用类型.现在,只要有任何代码调用你的DoThis<T>()
方法,它就必须提供一个替换T的类.例如,如果我打电话给你的DoThis<T>()
方法,那么我将不得不称之为:
DoThis<MyClass>();
Run Code Online (Sandbox Code Playgroud)
如果您的方法如下所示:
public IList<T> DoThis<T>() where T : class
{
T variablename = new T();
// other uses of T as a type
}
Run Code Online (Sandbox Code Playgroud)
然后在你的方法中出现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
}
Run Code Online (Sandbox Code Playgroud)