【问题标题】:Why ArrayList implement IList, ICollection, IEnumerable?为什么ArrayList实现IList、ICollection、IEnumerable?
【发布时间】:2010-11-12 23:31:09
【问题描述】:

ArrayList 声明它实现了IListICollectionIEnumeralbe 接口。

为什么不只实现IList,因为IList也是派生自ICollection,而ICollection又派生自IEnumerable

这种声明的目的是什么? .NET BCL中有很多这样的情况。

【问题讨论】:

    标签: c# interface


    【解决方案1】:

    没有有效的区别。我相信额外的声明是为了清楚起见。

    在 Reflector 中检查时,在代码中实现 IList 的类与在代码中声明实现所有 IlistICollectionIEnumerable 的类具有相同的接口声明列表。

    【讨论】:

      【解决方案2】:

      使用以下代码:

      interface I1 { }
      interface I2 : I1 { }
      
      class Foo: I2 { }
      

      如果你通过反射看 Foo 你会发现

      class Foo: I2, I1 { }
      

      这也是有效的编译并给出相同的结果。
      所以区别是没有实际意义的,在记录 Foo 时,您不妨同时使用两个接口编写它。

      另请参阅 SO 问题:Why collections classes in C# (like ArrayList) inherit from multiple interfaces if one of these interfaces inherits from the remaining?

      【讨论】:

        【解决方案3】:

        我不太确定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
        

        【讨论】:

          【解决方案4】:
          1. IEnumerable - 支持 foreach 语句
          2. ICollection - 支持在数组列表中添加单个或多个项目

          【讨论】:

          • 提问者并没有问他们是做什么用的 - 是在问为什么他们被明确列为正在实施,而他们已经通过 IList 上的继承实现了
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-12-07
          • 2011-07-29
          • 1970-01-01
          • 1970-01-01
          • 2011-01-22
          • 1970-01-01
          相关资源
          最近更新 更多