如何解决Generic.IList <T> .this []和IList.this []之间的调用歧义?
我有一个实现接口的集合,该接口扩展了IList <T>和List。
public Interface IMySpecialCollection : IList<MyObject>, IList { ... }
这意味着我有两个版本的索引器。
我希望使用通用实现,因此我通常会实现该实现:
public MyObject this[int index] { .... }
我只需要IList版本进行序列化,因此我明确实现了它,以使其保持隐藏状态:
object IList.this[int index] { ... }
但是,在我的单元测试中,以下内容
MyObject foo = target[0];
导致编译器错误
The call is ambiguous between the following methods or properties
我对此感到有些惊讶;我相信我以前做过,而且效果很好。我在这里想念什么?如何使IList <T>和IList共存于同一接口中?
编辑IList <T>不实现IList,并且我必须实现IList进行序列化。我对变通办法不感兴趣,我想知道我所缺少的。
再次编辑:我不得不从界面中删除IList并将其移到我的课程上。我不想这样做,因为实现该接口的类最终将被序列化为Xaml,这需要集合来实现IDictionary或者IList ...
解决方案
回答
List <T>暗含了IList,因此在同一个类中同时使用两者是一个坏主意。
回答
不幸的是,我们不能使用相同的参数列表声明两个索引器。以下段落摘自《 C编程指南》中的使用索引器的"备注"部分:
The signature of an indexer consists of the number and types of its formal parameters. It does not include the indexer type or the names of the formal parameters. If you declare more than one indexer in the same class, they must have different signatures.
如果要使用第二个索引器,则必须声明一组不同的参数。
回答
将通用实现更改为...
T IList<T>.this[int index] { get; set; }
这明确指出了哪个"这个"是哪个。
回答
你不能这样做
公共接口IMySpecialCollection:IList <MyObject>,IList {...}
但是我们可以使用类来做我们想做的事情,我们将需要明确其中一个接口的实现。在我的示例中,我明确列出了IList。
公共类MySpecialCollection:IList <MyObject>,IList {...}
IList <object> myspecialcollection = new MySpecialCollection(); IList list =(IList)myspecialcollection;
我们是否考虑过让IMySpecialCollection实现ISerializable进行序列化?
支持多种收集类型对我来说似乎有点不对劲。我们可能还想看看将IList强制转换为IEnumerable进行序列化,因为IList只包装了IEnumerable和ICollection。
回答
这是我的问题的骗子
总而言之,如果我们这样做,它将解决问题:
public Interface IMySpecialCollection : IList<MyObject>, IList { new MyObject this[int index]; ... }