Csharp/C#教程:用于公开通用接口的非generics版本的模式分享


用于公开通用接口的非generics版本的模式

假设我有以下界面来显示分页列表

public interface IPagedList { IEnumerable PageResults { get; } int CurrentPageIndex { get; } int TotalRecordCount { get; } int TotalPageCount { get; } int PageSize { get; } } 

现在我想创建一个分页控件

 public class PagedListPager { public PagedListPager(IPagedList list) { _list = list; } public void RenderPager() { for (int i = 1; i < list.TotalPageCount; i++) RenderLink(i); } } 

分页控制对T (列表的实际内容)没有兴趣。 它只需要页面数,当前页面等。因此, PagedListPager是通用的唯一原因是它将使用通用的IPagedList参数进行编译。

这是代码味吗? 我是否应该关心我有效地使用冗余通用?

在这种情况下是否有标准模式用于公开接口的其他非generics版本,因此我可以删除寻呼机上的generics类型?

 public class PagedListPager(IPagedList list) 

编辑

我想我也会添加当前解决这个问题的方法并邀请评论是否是一个合适的解决方案:

 public interface IPagedList // non-generic version { IEnumerable PageResults { get; } int CurrentPageIndex { get; } int TotalRecordCount { get; } int TotalPageCount { get; } int PageSize { get; } } public class ConcretePagedList : IPagedList, IPagedList { #region IPagedList Members public IEnumerable PageResults { get; set; } public int CurrentPageIndex { get; set; } public int TotalRecordCount { get; set; } public int PageSize { get; set; } #endregion #region IPagedList Members IEnumerable IPagedList.PageResults { get { return PageResults.Cast(); } } #endregion } 

现在我可以将ConcretePagedList传递给非generics类/函数

我的方法是使用new来重新声明PageResults ,并将T作为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; } } 

然而,这将需要“显式接口实现”,即

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

此方法通过通用API和非通用API使API完全可用。

一种选择是创建2个接口,以便:

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

然后你的控制:

 public class PagedListPager(IPagedListDetails details) 

首先定义两个接口

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

如您所见,IPagedList源自IPageSpecification。 在您的方法中,仅使用IPageSpecification作为参数。 在其他情况下,IPagedList – IPagedList的实现者也将包含来自IPageSpecification的数据

上述就是C#学习教程:用于公开通用接口的非generics版本的模式分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1018214.html

(0)
上一篇 2022年1月3日
下一篇 2022年1月3日

精彩推荐