public class GenericList<T>
{
void Add(T input) { }
}
class TestGenericList
{
private class ExampleClass { }
static void Main()
{
GenericList<int> list1 = new GenericList<int>();
GenericList<string> list2 = new GenericList<string>();
GenericList<ExampleClass> list3 = new GenericList<ExampleClass>();
}
}
|
static void Swap<T>(ref T lhs, ref T rhs)
{
T temp;
temp = lhs;
lhs = rhs;
rhs = temp;
}
|
class BaseNode { }
class BaseNodeGeneric<T> { }
class NodeConcrete<T> : BaseNode { }
class NodeClosed<T> : BaseNodeGeneric<int> { }
class NodeOpen<T> : BaseNodeGeneric<T> { }
|
class EmployeeList<T> where T : Employee, IEmployee, System.IComparable<T>, new() {}
|
约束 | 说明 |
---|---|
T:结构web |
类型参数必须是值类型。能够指定除 Nullable 之外的任何值类型。有关更多信息,请参见使用可空类型(C# 编程指南)。编程 |
T:类数组 |
类型参数必须是引用类型,包括任何类、接口、委托或数组类型。安全 |
T:new()函数 |
类型参数必须具备无参数的公共构造函数。当与其余约束一块儿使用时,new() 约束必须最后指定。性能 |
T:<基类名>spa |
类型参数必须是指定的基类或派生自指定的基类。设计 |
T:<接口名称>orm |
类型参数必须是指定的接口或实现指定的接口。能够指定多个接口约束。约束接口也能够是泛型的。对象 |
T:U |
为 T 提供的类型参数必须是为 U 提供的参数或派生自为 U 提供的参数。这称为裸类型约束。 |
class List<T>
{
void Add<U>(List<U> items) where U : T {}
}
|
public class SampleClass<T, U, V> where T : V { }
|