List covariance

How can we properly design the next model? I have two class libraries. Library 2 has a link to library 1. But in library 1 there is no link to library 2.

Library 1:

public class BaseData
{
   /*Some Properties*/
}

public class BaseGroup
{
   /*Some data*/
   public List<BaseData> DataList;
}

Library 2:

public class ChildData : BaseData
{
   /*Some more data*/
}

public class ChildGroup
{
   /*Some more data*/
   public List<ChildData> DataList;
}

How can I create these models so that I have one list. The list can be run in Library 1 and later, updated in Library 2. Also from Library 2 I need to pass the object ChildGroupto the methods of library 1, which takes BaseGroupas an argument.

+4
source share
1 answer

List<T> - , . List<Apple> List<Fruit>, list.Add(new Orange()) , .

, baseGroup , . childGroup:

, , .NET:

public class BaseData {}

public class BaseGroup<T> where T : BaseData
{
    public List<T> DataList;
}

public class ChildData : BaseData {}

public class ChildGroup : BaseGroup<ChildData>
{
    // No need for a separate list here
}
+13

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


All Articles