【问题标题】:.net framework List<T> inheritance [duplicate].net 框架 List<T> 继承 [重复]
【发布时间】:2016-04-07 02:40:51
【问题描述】:

MS源码here

.net中List&lt;T&gt;类继承两个接口 (IList&lt;T&gt;System.Collections.IList

它实现了两个方法添加方法

public void Add(T item) {
        if (_size == _items.Length) EnsureCapacity(_size + 1);
        _items[_size++] = item;
        _version++;
    }

int System.Collections.IList.Add(Object item)
    {
        ThrowHelper.IfNullAndNullsAreIllegalThenThrow<T>(item, ExceptionArgument.item);


        try { 
            Add((T) item);            
        }
        catch (InvalidCastException) { 
            ThrowHelper.ThrowWrongValueTypeArgumentException(item, typeof(T));            
        }

        return Count - 1;
    }

第一个方法是公共的,第二个是私有方法。

IList 没有 add 方法,但 System.Collections.IList 有

从 System.Collections.IList 继承是什么概念?

【问题讨论】:

  • 明确一点,类实现接口并从基类继承。类不继承接口。 (虽然接口可以从基本接口继承)。
  • List&lt;T&gt; 不从IList&lt;T&gt;IList继承,它实现它们,因为它们是接口,而不是类。您可以实现任意数量的接口——这不是“多重继承”。
  • 第二个不是私有的,它只是 System.Collections.IList.Add 方法的显式实现
  • "从System.Collections.IList继承是什么概念?" - 这样List&lt;T&gt; 就可以在任何需要System.Collections.IList 类型的地方使用——这在使用非泛型代码时尤其重要。就这么简单。

标签: c# .net multiple-inheritance


【解决方案1】:

首先,正如其他人已经指出的那样,类实现接口而不是继承它们。

int System.Collections.IList.Add(Object item)

这里的类显式地实现了接口的 Add() 方法。与隐式接口实现相反,此类方法只能使用接口引用而不是类引用来访问。隐式和显式接口实现的详细区别请参考这里here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-19
    • 1970-01-01
    • 2011-07-09
    • 1970-01-01
    • 2010-10-28
    • 1970-01-01
    • 2013-08-03
    • 2010-11-05
    相关资源
    最近更新 更多