使用泛型类型的超类的通用方法?

Sha*_*ica 1 c# generics

假设我有一个泛型类:

public class MyGenericClass<T> { 
  ...
}
Run Code Online (Sandbox Code Playgroud)

现在在这个类中,我想要一个允许我与另一个泛型进行交互的方法,该泛型可以是泛型类型T或任何超类T,例如:

public void DoSomething<T1>(List<T1> things) 
  where T : T1 // of course this won't compile
{
  ...
}
Run Code Online (Sandbox Code Playgroud)

你会怎么做?

Jon*_*eet 5

你不能,我害怕.你最接近的可能是在非泛型类中有一个方法 - 可能是一个扩展方法:

public static MyGenericClassExtensions
{
    public static void DoSomething<T, T1>(this MyGenericClass<T> @this,
                                          List<T1> things)
        where T : T1
    {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

这很好,因为它同时引入了两个类型参数.

当然,另一种方法是将方法作为实例方法保留在MyGenericClass<T>没有约束的情况下,并在执行时检查约束.就编译时安全性和泛型的一般声明性而言,这将是不幸的,但最终可能会为您做得更好.