作为函数参数继承泛型

本文关键字:继承 泛型 参数 函数 | 更新日期: 2023-09-27 17:50:55

我该怎么做呢?

class A { }
class B : A { }
class X<T> where T : A { }
class Y<T> : X<T> where T : A { }
private static void f(X<A> x) { }
public static void Main(string[] args)
{
    Y<B> y = new Y<B>();
    f(y); // Compiler error here
}

Y继承自X, B继承自A,但没有被编译

作为函数参数继承泛型

将函数定义更改为:

private static void f<T>(X<T> x) where T : A { }

正如您所定义的那样,您说f()必须传递X<A>的实例。通过我在这里展示的定义,你说f()取任何有X<A>作为父类的类。