为什么数组实现 IList? [英] Why array implements IList?

查看:26
本文介绍了为什么数组实现 IList?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

System.Array类的定义

public abstract class Array : IList, ...

理论上,我应该能写出这点并且开心

Theoretically, I should be able to write this bit and be happy

int[] list = new int[] {};
IList iList = (IList)list;

我也应该能够从 iList 调用任何方法

I also should be able to call any method from the iList

 ilist.Add(1); //exception here

我的问题不是为什么会出现异常,而是为什么 Array 实现 IList?

My question is not why I get an exception, but rather why Array implements IList?

推荐答案

因为数组允许通过索引快速访问,而 IList/IList 是唯一的支持这一点的集合接口.所以也许您真正的问题是为什么没有带有索引器的常量集合的接口?"对此我没有答案.

Because an array allows fast access by index, and IList/IList<T> are the only collection interfaces that support this. So perhaps your real question is "Why is there no interface for constant collections with indexers?" And to that I have no answer.

集合也没有只读接口.而且我错过的不仅仅是索引器界面的常量大小.

There are no readonly interfaces for collections either. And I'm missing those even more than a constant sized with indexers interface.

IMO 应该有更多(通用)集合接口,具体取决于集合的特性.并且名称也应该不同,List 对于带有索引器的东西来说真是愚蠢的 IMO.

IMO there should be several more (generic) collection interfaces depending on the features of a collection. And the names should have been different too, List for something with an indexer is really stupid IMO.

  • 只是枚举IEnumerable
  • 只读但没有索引器(.Count、.Contains、...)
  • 可调整大小但没有索引器,即设置为 (Add, Remove,...) 当前 ICollection
  • Readonly with indexer (indexer, indexof,...)
  • 带有索引器的常量大小(带有 setter 的索引器)
  • 可变大小与索引器(插入,...)当前 IList

我认为目前的收藏界面设计很糟糕.但是由于它们具有告诉您哪些方法有效的属性(这是这些方法的契约的一部分),因此它并没有违反替换原则.

I think the current collection interfaces are bad design. But since they have properties telling you which methods are valid (and this is part of the contract of these methods), it doesn't break the substitution principle.

这篇关于为什么数组实现 IList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆