2015-07-08 12 views
2

Я прочитал этот код:Что такое реализация List?

List<long> userIdList = new List<long>(); 

Но я подскочил к определению (использование VS2012) из ​​ListSystem.Collections.Generic), я нашел:

public class List<T> : IList<T>, ICollection<T>, IEnumerable<T>, IList, ICollection, IEnumerable 
{ 
    // Summary: 
    //  Initializes a new instance of the System.Collections.Generic.List<T> class 
    //  that is empty and has the default initial capacity. 
    [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] 
    public List(); 
    // 
    // Summary: 
    //  Initializes a new instance of the System.Collections.Generic.List<T> class 
    //  that contains elements copied from the specified collection and has sufficient 
    //  capacity to accommodate the number of elements copied. 
    // 
    // Parameters: 
    // collection: 
    //  The collection whose elements are copied to the new list. 
    // 
    // Exceptions: 
    // System.ArgumentNullException: 
    //  collection is null. 
    public List(IEnumerable<T> collection); 
    // 
    // Summary: 
    //  Initializes a new instance of the System.Collections.Generic.List<T> class 
    //  that is empty and has the specified initial capacity. 
    // 
    // Parameters: 
    // capacity: 
    //  The number of elements that the new list can initially store. 
    // 
    // Exceptions: 
    // System.ArgumentOutOfRangeException: 
    //  capacity is less than 0. 
    [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] 
    public List(int capacity); 

    // Summary: 
    //  Gets or sets the total number of elements the internal data structure can 
    //  hold without resizing. 
    // 
    // Returns: 
    //  The number of elements that the System.Collections.Generic.List<T> can contain 
    //  before resizing is required. 
    // 
    // Exceptions: 
    // System.ArgumentOutOfRangeException: 
    //  System.Collections.Generic.List<T>.Capacity is set to a value that is less 
    //  than System.Collections.Generic.List<T>.Count. 
    // 
    // System.OutOfMemoryException: 
    //  There is not enough memory available on the system. 
    public int Capacity { get; set; } 
    // 
    // Summary: 
    //  Gets the number of elements actually contained in the System.Collections.Generic.List<T>. 
    // 
    // Returns: 
    //  The number of elements actually contained in the System.Collections.Generic.List<T>. 
    public int Count { get; } 

    // Summary: 
    //  Gets or sets the element at the specified index. 
    // 
    // Parameters: 
    // index: 
    //  The zero-based index of the element to get or set. 
    // 
    // Returns: 
    //  The element at the specified index. 
    // 
    // Exceptions: 
    // System.ArgumentOutOfRangeException: 
    //  index is less than 0.-or-index is equal to or greater than System.Collections.Generic.List<T>.Count. 
    public T this[int index] { get; set; } 

    // Summary: 
    //  Adds an object to the end of the System.Collections.Generic.List<T>. 
    // 
    // Parameters: 
    // item: 
    //  The object to be added to the end of the System.Collections.Generic.List<T>. 
    //  The value can be null for reference types. 
    public void Add(T item); 

    ... 

Это не интерфейс или абстрактный, но это Безразлично У меня есть тело функции (для любого метода в этом классе). Я знаю ArrayList и LinkedList, но для List, я понятия не имею о его реализации.

Мой вопрос:

  1. Где реализация List?
  2. Если List равно ArrayList или что-то в этом роде, почему .net позволит двум классам, которые равны функции, но другому имени? Если List не соответствует любому другому классу в .NET, то почему бы назвать его таким неоднозначным именем?

MSDN states:

Класс Список является общим эквивалентом класса ArrayList. Он реализует общий интерфейс IList, используя массив, размер которого динамически увеличивается по мере необходимости.

Так что, я думаю, что это плохое имя ...

+2

http://referencesource.microsoft.com/#mscorlib/system/collections/generic/list.cs,cf7f4095e4de7646 – MarcinJuraszek

+0

Исходный код находится здесь: http://reflector.webtropy.com/default.aspx/Net/Net/3 @ 5 @ 50727 @ 3053/DEVDIV/depot/DevDiv/релизы/whidbey/netfxsp/ndp/clr/src/BCL/System/Collections/Generic/List @ cs/2/List @ cs - взято из http://stackoverflow.com/questions/14913640/which-algorithm-is-used-in-listt-to-dynamically-allocate-memory – Rob

+0

Что заставляет вас сказать, что 'List' является двусмысленным именем? – Enigmativity

ответ

10

Реализация List<T> не может быть показана в Visual Studio, потому что у нее нет исходного кода. Он просто показывает схему класса (поэтому Visual Studio ставит [метаданные] поверх «файла кода» при нажатии F12).

Фактический источник можно найти на referencesource.microsoft.com.

Если список равен ArrayList или что-то еще, почему .net позволит двум классам, которые равны функции, но другому имени? Если List не соответствует любому другому классу в .NET, то почему бы назвать его таким неоднозначным именем?

Нет, они не то же самое. ArrayList является нерегулярной реализацией списка, в то время как List<T>являетсяgeneric и, следовательно, строго типизирован.

Что касается неоднозначного имени: я думаю, что Microsoft прав в своем названии List. ArrayList было ужасным именем. Это подчеркивает реализацию слишком много. Тебе все равно, что за ним есть массив: тебе просто List. Учитывая, что имя было доступно, это было хорошим вариантом для имени.

4

Где реализация списка?

Что вы видите, это то, что VS позволяет вам видеть, это не код, а краткое описание каждой документации по методам. Если вы хотите этот код, то введите код available here

Есть ли список и массив? Если List не соответствует любому другому классу в .NET, то почему бы назвать его таким неоднозначным именем?

List<T> не соответствует ArrayList. A List<T> строго типизирован, в то время как ArrayList использует object как внутреннюю коллекцию, поэтому не сильно типизирован.

Первые воплотились в жизнь, когда в .NET были представлены generics.

Я не думаю, что что-то двусмысленное о List<T>. Это список, который может содержать любой параметр в качестве внутреннего хранилища, например List<int>, List<string> или List<Foo>.

Смежные вопросы