List< T>真的是C#中的秘密数组? [英] Is List<T> really an undercover Array in C#?

查看:66
本文介绍了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() 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.

这篇关于List&lt; T&gt;真的是C#中的秘密数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆