【发布时间】:2011-10-05 01:33:46
【问题描述】:
我必须同时使用不同的通用参数实现 2 个接口,如下所示。我对此感到困惑。我不知道其中哪一个在 foreach 中迭代自己。现在我明白第一个是隐式选择的。
我尝试过new BarList().GetEnumerator(),但我无法在方法级别指定类型参数。
我发现的唯一解决方案是将其转换为类似界面(new BarList() as IEnumerable<string>)
在对它感到困惑之后。我只是想知道这个设计不是很好的主意吗?我必须避免再次实现相同的通用接口?
class Program
{
static void Main(string[] args)
{
foreach (var item in new BarList())
{
}
}
}
class BarList: IEnumerable<string>, IEnumerable<int>
{
public IEnumerator<int> GetEnumerator()
{
throw new NotImplementedException();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
IEnumerator<string> IEnumerable<string>.GetEnumerator()
{
throw new NotImplementedException();
}
}
编辑:
让我解释一下我为什么要这样做。
我必须实现从IList<T> 继承的IPagedList<T> 接口。我想编写将其转换为我的视图模型的扩展方法。如下所示
GetAll().ToPagedList(pageindex);//这是返回 IPagedList 然后我想像下面这样使用它;
GetAll().ToPagedList(pageindex).ToViewModel<T,TViewModel>();
为了实现这一点,我尝试通过该扩展方法返回IPagedList<ViewModel>。在这种情况下,我必须使用不同的参数实现 IPagedList 2 次。但是这种策略使事情变得混乱。这就是它的原因。
【问题讨论】:
-
你能贴出 IPagedList
或 PagedList 的链接/代码吗?