[英]Pattern for exposing non-generic version of generic interface
假设我有以下用于公开分页列表的界面
public interface IPagedList<T>
{
IEnumerable<T> PageResults { get; }
int CurrentPageIndex { get; }
int TotalRecordCount { get; }
int TotalPageCount { get; }
int PageSize { get; }
}
现在我想创建一个分页控件
public class PagedListPager<T>
{
public PagedListPager<T>(IPagedList<T> list)
{
_list = list;
}
public void RenderPager()
{
for (int i = 1; i < list.TotalPageCount; i++)
RenderLink(i);
}
}
分页控件对T
(列表的实际内容)没有兴趣。 它只需要页数、当前页等。因此PagedListPager
是通用的唯一原因是它可以使用通用IPagedList<T>
参数进行编译。
这是代码味道吗? 我应该关心我实际上有一个冗余的泛型吗?
在这种情况下是否有标准模式可以公开接口的附加非泛型版本,以便我可以删除寻呼机上的泛型类型?
public class PagedListPager(IPagedList list)
编辑
我想我还会添加我解决此问题的当前方式,并邀请评论它是否是一个合适的解决方案:
public interface IPagedList // non-generic version
{
IEnumerable<object> PageResults { get; }
int CurrentPageIndex { get; }
int TotalRecordCount { get; }
int TotalPageCount { get; }
int PageSize { get; }
}
public class ConcretePagedList<T> : IPagedList<T>, IPagedList
{
#region IPagedList<T> Members
public IEnumerable<T> PageResults { get; set; }
public int CurrentPageIndex { get; set; }
public int TotalRecordCount { get; set; }
public int PageSize { get; set; }
#endregion
#region IPagedList Members
IEnumerable<object> IPagedList.PageResults
{
get { return PageResults.Cast<object>(); }
}
#endregion
}
现在我可以将ConcretePagedList<T>
传递给非泛型类/函数
我的方法是使用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<T> : IPagedList
{
new IEnumerable<T> PageResults { get; }
}
然而,这将需要“显式接口实现”,即
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); }
}
}
这种方法使 API 通过通用和非通用 API 完全可用。
一种选择是创建 2 个接口,例如:
public interface IPagedListDetails
{
int CurrentPageIndex { get; }
int TotalRecordCount { get; }
int TotalPageCount { get; }
int PageSize { get; }
}
public interface IPagedList<T> : IPagedListDetails
{
IEnumerable<T> 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<T> : IPageSpecification
{
IEnumerable<T> PageResults { get; }
}
如您所见,IPagedList 派生自 IPageSpecification。 在您的方法中,仅使用 IPageSpecification 作为参数。 在其他情况下,IPagedList - IPagedList 的实现者也将包含来自 IPageSpecification 的数据
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.