Why doesn't the following compile? (includes generics and inheritance in C #)

This compiles:

    class ReplicatedBaseType
    {
    }

    class NewType: ReplicatedBaseType
    {
    }

    class Document
    {
    ReplicatedBaseType BaseObject;

    Document()
    {
     BaseObject = new NewType();
    }
}

code>

But this is not so:

    class DalBase<T> : where T: ReplicatedBaseType
    {
    }

    class DocumentTemplate
    {
    DalBase<ReplicatedBaseType> BaseCollection;
    DocumentTemplate ()
    {
    BaseCollection= new DalBase<NewType>(); // Error in this line. It seems this is not possible
    }
    }

What reason?

+3
source share
5 answers

The difference exists in C # 4.0 for .NET 4), but is limited to interfaces and the use of in/ out(oh and arrays of reference types). For example, to make a covariant sequence:

class DalBase<T> : IEnumerable<T> where T: ReplicatedBaseType
{
    public IEnumerator<T> GetEnumerator() {throw new NotImplementedException();}
    IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); }
}

class DocumentTemplate
{
    IEnumerable<ReplicatedBaseType> BaseCollection;
    DocumentTemplate()
    {
        BaseCollection = new DalBase<NewType>(); // 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.

+6
source

As Andrei says, you want (general) covariance. However:

  • Total variance is only supported in C # 4
  • Generic class not supported in classes
  • .

, , DalBase<T> :

void AddEntity(T entity)

- , , , , :

DalBase<Fruit> fruitDal = new DalBase<Banana>();
fruitDal.AddEntity(new Apple());

- , .

, , - . NDC 2010 "". Eric Lippert - , ;)

+8

, DalBase<NewType> DalBase<ReplicatedBaseType> - co/contra-variance. # 4 , .

+2

, , "" # 4.0 http://blog.t-l-k.com/dot-net/2009/c-sharp-4-covariance-and-contravariance

, ( , ). # (< = 3,0) .

, . ยง6.1.6. #

+1

VS2010, net framework 4

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
    class ReplicatedBaseType
    {
    }

    class NewType : ReplicatedBaseType
    {
    }

    class Document
    {
        ReplicatedBaseType BaseObject;

        Document()
        {
            BaseObject = new NewType();
        }
    }
    interface DalBase<out T>  where T: ReplicatedBaseType
    {
    }

    class DalBaseExample<T> : DalBase<T> where T: ReplicatedBaseType
    {

    }
    class DocumentTemplate
    {
        DalBase<ReplicatedBaseType> BaseType;
        DocumentTemplate ()
        {
            BaseType = new DalBaseExample<NewType>(); // no error here
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
        }
    }
}
0

Source: https://habr.com/ru/post/1751731/


All Articles