泛型的分层使用

时间:2016-12-23 14:25:50

标签: c# generics hierarchical

当尝试在一个以上的子类层上“传播”泛型类型时,我遇到了一些问题。 我有三层课程: GenericResponseDtoMapper<T>是一个抽象类,TGenericSearchResponseDto

我有两个扩展GenericResponseDtoMapper的子类:SimpleResponseDtoMapperGroupedResponseDtoMapper。 在这两个子类中,我被迫指定泛型类型;因为我必须写:

SimpleResponseDtoMapper : GenericResponseDtoMapper<GenericResponseDtoMapper>

最后,我有一些扩展SimpleResponseDtoMapper的类和一些扩展GroupedResponseDtoMapper的其他类。 我的问题是我无法在此级别指定GenericSearchResponseDto的子类型。

那么,我如何管理泛型类型以便为第一层和第二层留下泛型类型,让较低级别的类使用指定类型的泛型类型?

以下是代码:

public abstract class GenericResponseDtoMapper<T> : IResponseDtoMapperDecorator where T : GenericSearchResponseDto
{
    protected List<T> items;

    public GenericResponseDtoMapper()
    {
        items = new List<T>();
    }

    public abstract IList<T> GetItems(IList<Entity.FullText_xml.DreDoc> documents);
}

Class SimpleResponseDtoBuilder:

public abstract class SimpleResponseDtoBuilder : GenericResponseDtoMapper<GenericSearchResponseDto>
{
    public SimpleResponseDtoBuilder() : base() { }

    public override IList<GenericSearchResponseDto> GetItems(IList<DreDoc> documents)
    {
        foreach (var doc in documents) 
        {
            var item = new GenericSearchResponseDto();

            item.IdDatabank = doc.Field.IdDatabank;
            item.IdDocMaster = doc.Field.IdDocMaster;
            item.DescDatabank = doc.Field.DescDatabank;
            item.Materie = doc.Field.MateriaAll.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries);
            item = setResponseParams(item, doc);

            items.Add(item);
        }

        return items;
    }

    public abstract GenericSearchResponseDto setResponseParams(GenericSearchResponseDto item, DreDoc doc);
}

最后具体实施:

public class GiurisprudenzaResponseDtoBuilder : SimpleResponseDtoBuilder
{
    private HighlightHelper _highLightHelper;

    private const string _BR = @"<br/>";

    public GiurisprudenzaResponseDtoBuilder() : base() 
    {
        _highLightHelper = new HighlightHelper();
    }

    public override IList<GiurisprudenzaSearchResponseDto> GetItems(IList<DreDoc> documents)
    {
        return base.GetItems(documents);
    }

    public override GiurisprudenzaSearchResponseDto setResponseParams(GiurisprudenzaSearchResponseDto item, DreDoc doc)
    {

        item.IdUnitaDoc = doc.Field.IdUnitaDoc;

        ... some item.Something = doc.Something...

        return item;
    }

UML Class Diagram

1 个答案:

答案 0 :(得分:0)

在C#中通过多个子类层传播泛型类型的方法如下:

public TopClass<T> where T : GenericType{
}

public MiddleClass<T> : TopClass<T> where T : GenericType{
}

public BottomClass : MiddleClass<SpecificType>{
}