C# 成员在实现IList时不可用
我试图创建一个实现IList的简单类。但是,除非我首先将DiskBackedCollection强制转换为IList,否则成员不可用。我怎样才能使它在没有铸造的情况下可用C# 成员在实现IList时不可用,c#,C#,我试图创建一个实现IList的简单类。但是,除非我首先将DiskBackedCollection强制转换为IList,否则成员不可用。我怎样才能使它在没有铸造的情况下可用 public partial class DiskBackedCollection<T> : IList<T> { private List<T> _underlyingList = new List<T>(); int IList<T>.Index
public partial class DiskBackedCollection<T> : IList<T>
{
private List<T> _underlyingList = new List<T>();
int IList<T>.IndexOf(T item)
{
return _underlyingList.IndexOf(item);
}
T IList<T>.this[int index]
{
get
{
return _underlyingList[index];
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
int ICollection<T>.Count
{
get
{
return _underlyingList.Count;
}
}
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return new DiskBackedCollectionEnumerator(this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return new DiskBackedCollectionEnumerator(this);
}
}
公共部分类DiskBackedCollection:IList
{
私有列表_underyinglist=新列表();
int IList.IndexOf(T项)
{
返回_underyinglist.IndexOf(项目);
}
T IList.此[int索引]
{
得到
{
返回_underyinglist[索引];
抛出新的NotImplementedException();
}
设置
{
抛出新的NotImplementedException();
}
}
int ICollection.Count
{
得到
{
返回_underyinglist.Count;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
返回新的DiskBackedCollectionEnumerator(此);
}
IEnumerator IEnumerable.GetEnumerator()
{
返回新的DiskBackedCollectionEnumerator(此);
}
}
这是因为每个成员前面都有
IList.
。去掉那个,他们就会出现
使用IList实现接口成员。在接口成员前面调用。实现接口要求的方法必须是公共的。你的不是 此外,您还需要删除显式实现:
public int Count
{
get
{
return _underlyingList.Count;
}
}
.我设法进入了我的脑海,这只是一个代码清晰的事情感谢您提供的链接。与您的问题无关,但它通常会简化您的代码以使用基类
集合
,该集合具有虚拟方法插入项
,removietem
etc,您可以为任何自定义功能重写它。@据我所知,Collection类使用一个内部列表来存储项。因此,最好使用该类向简单列表中添加验证。然而,由于我将要从磁盘(数百万行)存储和检索数据,我不希望它存储在内部列表中。从我上面的实现来看,您是正确的,但它还远远没有完成。@Lee,您是对的,只是为了学究,它使用了一个内部的IList
,而不必是一个列表。我的评论是基于你上面的实现(_underyinglist)。@DaveShaw如果你没有公开实现接口,编译器应该抱怨(在这种情况下,从技术上讲你不会实现它)。