Pattern for exposing non-generic version of generic interface

后端 未结 3 1937
梦谈多话
梦谈多话 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 : IPagedList
    {
        new IEnumerable PageResults { get; }
    }  
    

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

    class Foo : IPagedList
    {
        /* skipped : IPagedList 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.

提交回复
热议问题