简体   繁体   English

为什么ArrayList实现IList,ICollection,IEnumerable?

[英]Why ArrayList implement IList, ICollection, IEnumerable?

ArrayList declares that it implements the IList , ICollection , and IEnumeralbe interfaces. ArrayList声明它实现了IListICollectionIEnumeralbe接口。

Why not only implement IList , because IList is also derived from ICollection , and ICollection is derived from IEnumerable . 为什么不实现IList ,因为IList也是从ICollection派生的,而ICollection是从IEnumerable派生的。

What's the purpose of this kind of declaration? 这种宣言的目的是什么? There are many cases like this in .NET BCL. 在.NET BCL中有很多这样的情况。

There is no effective difference. 没有有效的区别。 I believe the extra declarations are there for clarity. 我相信额外的声明是为了清楚。

When checked in Reflector, classes which in code implement IList have the same interface declaration list as classes which in code declare implementing all of Ilist , ICollection and IEnumerable . 在Reflector中检查时,代码实现IList的类具有与代码声明实现IlistICollectionIEnumerable所有类相同的接口声明列表。

With the following code: 使用以下代码:

interface I1 { }
interface I2 : I1 { }

class Foo: I2 { }

If you look at Foo through reflection you will find 如果你通过反思看Foo,你会发现

class Foo: I2, I1 { }

Which is also valid to compile and gives the same result. 哪个也适用于编译并给出相同的结果。
So the difference is moot, and in documenting Foo you might as well write it with both interfaces. 所以区别是没有意义的,在记录Foo时你也可以用两个接口来编写它。

Also see the SO question: Why collections classes in C# (like ArrayList) inherit from multiple interfaces if one of these interfaces inherits from the remaining? 另请参阅SO问题: 为什么C#中的集合类(如ArrayList)从多个接口继承,如果其中一个接口继承其余接口?

I am not so sure that ArrayList has separate implementations of the interfaces. 我不太确定ArrayList是否有单独的接口实现。 Consider the following code: 请考虑以下代码:

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; }
}

The MyClass type implements only the ISub interface directly. MyClass类型直接实现ISub接口。 However, if you compile the code into an assembly, and then add that assembly as reference in another project, open the Object Browser and examine the base types for MyClass , it will feature something like this: 但是,如果将代码编译为程序集,然后将该程序集作为引用添加到另一个项目中,请打开对象浏览器并检查MyClass的基本类型,它的特征如下:

Base Types
 |- ISub
 |    |- IBase
 |- IBase
 |- Object
  1. IEnumerable - To support the foreach statement IEnumerable - 支持foreach语句
  2. ICollection - To support add single or multiple item in arraylist ICollection - 支持在arraylist中添加单个或多个项目

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM