假设我有一个通用类:
public class MyGenericClass<T> {
...
}
现在在这个类中,我想要一个允许我与另一个泛型交互的方法,它可以是泛型类型T
或任何超类T
,例如:
public void DoSomething<T1>(List<T1> things)
where T : T1 // of course this won't compile
{
...
}
你会怎么做?
你不能,我害怕。您最接近的方法是在非泛型类中有一个方法 - 可能是一个扩展方法:
public static MyGenericClassExtensions
{
public static void DoSomething<T, T1>(this MyGenericClass<T> @this,
List<T1> things)
where T : T1
{
...
}
}
这很好,因为它同时引入了两个类型参数。
当然,另一种方法是将方法作为实例方法保留在 内MyGenericClass<T>
,没有约束,并在执行时检查约束。就泛型的编译时安全性和一般声明性而言,这将是不幸的,但它最终可能对您更好。
@JonSkeet 的回答一如既往地正确,但我确实找到了另一种方法来做到这一点,而不会导致我的代码发生任何剧变。我创建了另一个泛型类并修改了现有的类,如下:
public class MyGenericClass<T, TBase>
where T : TBase
{
public void DoSomething(List<TBase> things)
{
...
}
}
public class MyGenericClass<T> : MyGenericClass<T, T>
{
...
}
通过这种方式,我获得了所需的功能,同时仍然保持向后兼容性,即所有使用原始单类型泛型的现有代码仍然可以工作。