Pattern for exposing non-generic version of generic interface

后端 未结 3 1934
梦谈多话
梦谈多话 2021-01-31 09:44

Say I have the following interface for exposing a paged list

public interface IPagedList
{
    IEnumerable PageResults { get; }
    int Current         


        
相关标签:
3条回答
  • 2021-01-31 10:05

    My approach here would be to use new to re-declare the PageResults, and expose the T as a Type:

    public interface IPagedList
    {
        int CurrentPageIndex { get; }
        int TotalRecordCount { get; }
        int TotalPageCount { get; }        
        int PageSize { get; }
    
        Type ElementType { get; }
        IEnumerable PageResults { get; }
    }   
    
    public interface IPagedList<T> : IPagedList
    {
        new IEnumerable<T> PageResults { get; }
    }  
    

    This will, however, require "explicit interface implementation", i.e.

    class Foo : IPagedList<Bar>
    {
        /* skipped : IPagedList<Bar> implementation */
    
        IEnumerable IPagedList.PageResults {
            get { return this.PageResults; } // re-use generic version
        }
        Type IPagedList.ElementType {
            get { return typeof(Bar); }
        }
    }
    

    This approach makes the API fully usable via both the generic and non-generic API.

    0 讨论(0)
  • 2021-01-31 10:16

    One option is to create 2 interfaces such that:

        public interface IPagedListDetails
        {
            int CurrentPageIndex { get; }
            int TotalRecordCount { get; }
            int TotalPageCount { get; }
            int PageSize { get; }
        }
    
        public interface IPagedList<T> : IPagedListDetails
        {
            IEnumerable<T> PageResults { get; }
        }
    

    And then your control:

    public class PagedListPager(IPagedListDetails details)
    
    0 讨论(0)
  • 2021-01-31 10:19

    Define two interfaces, first

        public interface IPageSpecification
        {
            int CurrentPageIndex { get; }
            int TotalRecordCount { get; }
            int TotalPageCount { get; }        
            int PageSize { get; }
        }   
    
    public interface IPagedList<T> : IPageSpecification
    {
        IEnumerable<T> PageResults { get; }
    }   
    

    As you see, IPagedList is derived from IPageSpecification. In your method, only use IPageSpecification as parameter. In other cases, IPagedList - implementers of IPagedList would also contain data from IPageSpecification

    0 讨论(0)
提交回复
热议问题