我建议避免使用非泛型语法的泛型类型,例如您给出的示例。但是,还有其他有用的案例。
例如,一般指定返回类型:
static T Create<T>() where T: Sample, new()
{
return new T();
}
// Calling code
Sample sample = Create<Sample>();
而不是
static object Create()
{
return new Sample();
}
// Calling code
Sample sample = (Sample) Create();
您还可以使用模板对一个类型设置多个限制。例如:
static T Create<T>() where T: IMyInterface, new()
{
return new T();
}
interface IMyInterface {}
class MyClass : IMyInterface { }
// Calling code.
MyClass myClass = Create<MyClass>();
这允许通用创建实现特定接口并具有通用构造函数的新类型。另外:
static void DoSomething<T>(T t) where T: IMyInterface1, IMyInterface2
{
t.MethodOnIMyInterface1();
t.MethodOnIMyInterface2();
}
interface IMyInterface1
{
void MethodOnIMyInterface1();
}
interface IMyInterface2
{
void MethodOnIMyInterface2();
}
class MyClass: IMyInterface1, IMyInterface2
{
// Method implementations omitted for clarity
}
// Calling code
MyClass myclass'
DoSomething(myclass); // Note that the compiler infers the type of T.
您可以在单个参数上要求多个接口,而无需 (1) 创建实现所有这些接口的新类型和 (2) 要求参数属于该类型。
正如@dcastro 在他/她的回答中指出的那样,泛型类型也可以告诉编译器要求类型相同。例如:
static void DoSomething<T>(T t1, T t2) where T: MyType
{
// ...
}
class MyType {}
class MyType1: MyType {}
class MyType2: MyType {}
// Calling code
MyType1 myType1;
MyType2 myType2;
DoSomething<MyType>(myType1, myType2);
编译器要求 t1 和 t2 是同一类型,但可以是继承 MyType 的任何类型。这在自动化单元测试框架(例如 NUnit 或 MSTest)中非常有用,可用于通用相等性和比较检查。