简体   繁体   中英

C# Generic class with collection of generics with another type property

I want to implement a universal generic type which could have a collection of another generic type and so one to infinity. The goal is to use this type to build hierarchical lists. So it can look something like this

public class BasicOverviewModel<T>
{
    public T OverViewModel { get; set; }

    public IEnumerable<BasicOverviewModel<new T>> ChildOverviewModelCollection { get; set; }
}

Is it possible at all, or maybe I choose a wrong solution? Thanks...

You have to use another generic type parameter, in this code called TChild .

It gets a little more complicated for the parent-child relationships. This is what I have come up with.

public interface IBasicOverviewModel
{
}

public class BasicOverviewModel<T, TChild> : IBasicOverviewModel where TChild : IBasicOverviewModel
{
    public T OverViewModel { get; set; }

    public IEnumerable<TChild> ChildOverviewModelCollection { get; set; }
}

public class EndpointOverviewModel<T> : IBasicOverviewModel
{
    public T OverViewModel { get; set; }
}

static class Program
{
    static void Main(string[] args)
    {
        var b = new BasicOverviewModel<string, BasicOverviewModel<int, EndpointOverviewModel<string>>>();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM