C# Generic Class Type parameter (cannot implicitly convert)

前端 未结 4 1687
小鲜肉
小鲜肉 2021-01-22 21:10

Scenario:

class A { }

class B : A { }

class C where T: A { }

Question

Why cant C<

相关标签:
4条回答
  • 2021-01-22 21:13

    Because C<A> is not C<B>

    The thing is; if you could do

    C<A> myA = new C<B>();
    myA.Add(new A());
    

    You'd have a problem, since B is A, but not A is B

    0 讨论(0)
  • 2021-01-22 21:21

    Use co-variant if you need to do this, and because co-variant just work only with interface and delegate, so define an interface with the magic word out instead of class:

    interface IC<out T> where T : A
    {
    }
    

    So, you can assign like you want:

    class CA : IC<A>
    {}
    
    class CB : IC<B>
    { }
    
    IC<A> x = new CA();
    IC<B> y = new CB();
    
    x = y;
    
    0 讨论(0)
  • 2021-01-22 21:23

    Why cant C<A> = C<B> when B is a subclass of A? B is subclass of A, but C<B> not a subclass of C<A>. There is no assignment compatibility between C<B> and C<A>.

    0 讨论(0)
  • 2021-01-22 21:39

    What you are asking for is Covariance and Contravariance in Generics which is only applicaple for interfaces and delegates. You can check this

    You can do the following in Framework >= 4:

    interface IC<out T> where T : A
    
    class C<T> : IC<T>  where T : A
    
    IC<A> ica = new C<B>();
    

    For your case you should extract an interface for class C

    0 讨论(0)
提交回复
热议问题