是否可以只为 List<T> 编写扩展方法,其中 T 是继承自 class K 的 class

is it possible to write an extension method only for List<T> where T is a class that inherits from class K

假设我有一个 Base Class:

public class Base{

}

我有一个 class 继承自 Base Class:

public class Derived: Base{

}

是否可以为 class 的 List<T> 编写一个扩展方法,它仅继承自基础 class,像这样:

public static string F(this List<Base> baseClass){
    return "This class inherits from Base Class";
}

扩展方法应该适用于 List<Base>List<Derived>。但它不适合我。

public static string F<T>(this List<T> baseClass)
  where T : Base
{
    return "This class inherits from Base Class";
}

该方法必须是通用的,因为 List<Derived> 不是 List<Base> 的子类型(也不是超类型)。

如果 IEnumerable 对你来说足够 并且 这是一个接口或委托方法,我认为你也可以用协变来解决这个问题。