c# - 具有泛型的C#类设计

标签 c# generics

我如何使以下类尽可能通用(最大程度地重用),而又不创建太多相同类型的类,尽管有一个额外的属性。

我想避免编写同一类的3个稍微不同的版本

没有子内容的1#类

public class Content
    {
         public string PageName { get; set; }
    }


2#带有子内容的类

public class Content
    {
         public string PageName { get; set; }

         public IList<Content> SubContent {get; set;}    //same as class

    }


具有其他类型的子内容的3#类

public class Content
        {
             public string PageName { get; set; }

             public IList<DetailContent> SubContent {get; set;} //Note the different def

        }


当然,我可以创建一个通用类,但是我对消费者感到困惑。推断该类是T类型,而实际上是需要该类型的Property

public class Content<T>
            {
                 public string PageName { get; set; }

                 public IList<T> SubContent {get; set;} //Note the different def

            }


不支持通用属性。那么,关于如何处理此问题,是否有任何模式或建议?

最佳答案

关于什么

public class Content
{
    public string PageName { get; set; }
}

public class ContentWithSubContent<T> : Content
{
    public IList<T> SubContent { get; set; }
}


并且如果您想访问不知道实际类型的SubContent,则可以使用

public class Content
{
    public string PageName { get; set; }
}

public interface IContentWithSubContent
{
    IEnumerable SubContent { get; }
}

public class ContentWithSubContent<T> : Content, IContentWithSubContent
{
    public IList<T> SubContent { get; set; }

    IEnumerable IContentWithSubContent SubContent 
    { 
        get { return this.SubContent; } 
    }
}


这样,您可以通过使用IContentsWithSubContent而不是Content来绕过泛型访问SubContent属性。

关于c# - 具有泛型的C#类设计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1464460/

相关文章:

c# - asp.net GridView 中select的命令是什么

c# - TPL 如何知道线程是否要求更多工作?

c# - Asp.Net Global.asax获取当前请求的Page对象

c# - 我可以在 XAML(.NET 4 Framework 之前)中指定泛型类型吗?

c# - 使用反射围绕通用存储库的通用包装器

c# - 通用接口(interface)方法的开放委托(delegate)

c# - 使用 Elasticsearch 将数组字段映射到 C# 字符串列表

c# - 测试依赖 MEF 注入(inject)的非导出类

c# - 返回泛型类型的函数,其值仅在运行时已知

c# - 通用的多个接口(interface)