型別約束(類和結構)
通過使用相應的約束 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
{
}
}