7 .net generics explicit interface
我有一个集合实现了一个扩展IList <T>和List的接口.
public Interface IMySpecialCollection : IList<MyObject>, IList { ... }
Run Code Online (Sandbox Code Playgroud)
这意味着我有两个版本的索引器.
我希望使用通用实现,所以我通常实现它:
public MyObject this[int index] { .... }
Run Code Online (Sandbox Code Playgroud)
我只需要IList版本进行序列化,所以我明确地实现它,以保持隐藏:
object IList.this[int index] { ... }
Run Code Online (Sandbox Code Playgroud)
但是,在我的单元测试中,以下内容
MyObject foo = target[0];
Run Code Online (Sandbox Code Playgroud)
导致编译器错误
以下方法或属性之间的调用不明确
我对此感到有些惊讶; 我相信我以前做过它并且工作正常.我在这里错过了什么?如何让IList <T>和IList在同一个界面中共存?
编辑 IList <T> 没有实现IList,我必须实现IList进行序列化.我对变通办法不感兴趣,我想知道我缺少什么.
再次编辑:我不得不从界面中删除IList并将其移到我的课堂上.我不想这样做,因为实现接口的类最终将被序列化为Xaml,这需要集合来实现IDictionary或IList ...
你不能这样做
public interface IMySpecialCollection : IList<MyObject>, IList { ... }
但是您可以对类执行您想要的操作,您需要显式地实现其中一个接口。在我的示例中,我明确了 IList。
public class MySpecialCollection : IList<MyObject>, IList { ... }
IList<object> myspecialcollection = new MySpecialCollection();
IList list = (IList)myspecialcollection;
您是否考虑过让 IMySpecialCollection 实现 ISerializable 来进行序列化?支持多种集合类型对我来说似乎有点错误。您可能还想考虑将 IList 转换为 IEnumerable 进行序列化,因为 IList 仅包装 IEnumerable 和 ICollection。