简体   繁体   English

C#通用类,包含具有其他类型属性的泛型集合

[英]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 . 您必须在此代码中使用另一个泛型类型参数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>>>();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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