【问题标题】:Inherited generic as a function parameter继承泛型作为函数参数
【发布时间】:2015-05-28 08:23:27
【问题描述】:

我怎样才能做到这一点?

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,但未编译。

【问题讨论】:

    标签: c# generics inheritance parameter-passing


    【解决方案1】:

    将函数定义改为:

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

    正如您所定义的,您是说必须将f() 传递给X&lt;A&gt; 的实例。通过定义如我在这里展示的那样,您是说f() 采用任何以X&lt;A&gt; 为父类的类。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-09
      相关资源
      最近更新 更多