类型约束(类和结构)
通过使用相应的约束 class
或 struct
,可以指定 type 参数是应该是引用类型还是值类型。如果使用这些约束,则必须先定义它们,然后才能列出所有其他约束(例如父类型或 new()
)。
// TRef must be a reference type, the use of Int32, Single, etc. is invalid.
// Interfaces are valid, as they are reference types
class AcceptsRefType<TRef>
where TRef : class
{
// TStruct must be a value type.
public void AcceptStruct<TStruct>()
where TStruct : struct
{
}
// If multiple constraints are used along with class/struct
// then the class or struct constraint MUST be specified first
public void Foo<TComparableClass>()
where TComparableClass : class, IComparable
{
}
}