Why does the following doesn't compile? (involves generics and inheritance in c#)

前端 未结 5 1716
野趣味
野趣味 2020-12-21 06:31

This compiles:

    class ReplicatedBaseType
    {
    }

    class NewType: ReplicatedBaseType
    {
    }

    class Document
    {
    ReplicatedBas         


        
5条回答
  •  一个人的身影
    2020-12-21 07:31

    Variance exists in C# 4.0 targetting .NET 4), but is limited to interfaces and usage of in/out (oh, and arrays of reference-types). For example, to make a covariant sequence:

    class DalBase : IEnumerable where T: ReplicatedBaseType
    {
        public IEnumerator GetEnumerator() {throw new NotImplementedException();}
        IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); }
    }
    
    class DocumentTemplate
    {
        IEnumerable BaseCollection;
        DocumentTemplate()
        {
            BaseCollection = new DalBase(); // Error in this line. It seems this is not possible
        }
    }
    

    But other than that... no. Stick to either non-generic lists (IList), or use the expected list type.

提交回复
热议问题