为什么ArrayList实现IList,ICollection,IEnumerable?
ArrayList
声明它实现了IList
, ICollection
和IEnumeralbe
接口。
为什么不实现IList
,因为IList
也是从ICollection
派生的,而ICollection
是从IEnumerable
派生的。
这种宣言的目的是什么? 在.NET BCL中有很多这样的情况。
使用以下代码:
interface I1 { } interface I2 : I1 { } class Foo: I2 { }
如果你通过反思看Foo,你会发现
class Foo: I2, I1 { }
哪个也适用于编译并给出相同的结果。
所以区别是没有意义的,在记录Foo时你也可以用两个接口来编写它。
另请参阅SO问题: 为什么C#中的集合类(如ArrayList)从多个接口inheritance,如果其中一个接口inheritance其余接口?
没有有效的区别。 我认为额外的声明是为了清楚。
在Reflector中检查时,代码实现IList
的类具有与代码声明实现所有Ilist
, ICollection
和IEnumerable
类相同的接口声明列表。
我不太确定ArrayList
是否有单独的接口实现。 请考虑以下代码:
public interface IBase { int SomeInt { get; set; } } public interface ISub : IBase { int SomeOther { get; set; } } public class MyClass : ISub { public int SomeOther { get; set; } public int SomeInt { get; set; } }
MyClass
类型直接实现ISub
接口。 但是,如果将代码编译为程序集,然后将该程序集作为引用添加到另一个项目中,请打开对象浏览器并检查MyClass
的基本类型,它将具有如下内容:
Base Types |- ISub | |- IBase |- IBase |- Object
- IEnumerable – 支持foreach语句
- ICollection – 支持在arraylist中添加单个或多个项目