List< T>真的是C#中的秘密数组?

List< T>真的是C#中的秘密数组?

问题描述:

我一直在使用ILSpy查看.NET库,并遇到了 System.Collections.Generic中的 List< T> 类定义。 code>命名空间。我看到该类使用了类似这样的方法:

I have been looking at .NET libraries using ILSpy and have come across List<T> class definition in System.Collections.Generic namespace. I see that the class uses methods like this one:

// System.Collections.Generic.List<T>
/// <summary>Removes all elements from the <see cref="T:System.Collections.Generic.List`1" />.</summary>
public void Clear()
{
    if (this._size > 0)
    {
        Array.Clear(this._items, 0, this._size);
        this._size = 0;
    }
    this._version++;
}

因此, Clear()$ c List< T> 类的$ c>方法实际上使用 Array.Clear 方法。我已经看到许多其他 List< T> 方法,它们在体内使用数组的东西。

So, the Clear() method of the List<T> class actually uses Array.Clear method. I have seen many other List<T> methods that use Array stuff in the body.

这是否意味着 List< T> 实际上是一个卧底数组,或者List仅使用部分数组方法?

Does this mean that List<T> is actually an undercover Array or List only uses some part of Array methods?

我知道列表是安全类型,不需要装箱/拆箱,但这让我有些困惑。

I know lists are type safe and don't require boxing/unboxing but this has confused me a bit.

列表类本身不是数组。换句话说,它不是从数组派生的。取而代之的是,它封装了一个数组,供实现使用以保存列表的成员元素。

The list class is not itself an array. In other words, it does not derive from an array. Instead it encapsulates an array that is used by the implementation to hold the list's member elements.

由于 List< T> 提供了对其元素的随机访问,并且这些元素的索引为 0..Count-1 ,使用数组存储元素是显而易见的实现。

Since List<T> offers random access to its elements, and those elements are indexed 0..Count-1, using an array to store the elements is the obvious implementation.