簡體   English   中英

List.Add() 方法內部

[英]List.Add() method internals

大多數 C# 開發人員都知道 System.Collections.Generic 包含列表 class。class 公開了 Add 方法,其實現如下:

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

我試圖了解這是如何工作的...我有一個 T 類型的本地數組,稱為“_items”,還有“_size”和“_version”變量。 當添加新項時,將創建一個新的 T 類型數組並稱為“arg_36_0”,將私有數組分配給新數組。 大小被復制; 然后局部大小增加,並且我們將傳遞的新項目分配給新創建的數組。 因此,在 function 完成后,本地“arg_36_0”數組將被刪除,該項目永遠不會分配給實際數組(稱為“_items”)。 我在這里錯過了什么? :)

您缺少引用類型語義。

T[] arg_36_0 = this._items

只會創建對完全相同數組的新引用。

引用類型的要點是,無論你在其中一個引用上做什么,都會反映在所有引用上。

所以arg_36_0[size] = item; 將改變底層數組。 你也可以這樣寫:

int size = this._size;
this._size = size + 1;
this._items[size] = item; // set the last element in the array
this._version++;

想象一下你有一個這樣的 class:

class MyClass
{
    int MyProperty { get; set; }
}

並創建它的一個實例:

var a = new MyClass();

如果您現在引入對 object 的第二個引用,您會看到ab的變化:

var b = a;
b.MyProperty = 3; // this changes the underlying object and thus is reflected in a also
Console.WriteLine(a.MyProperty); // prints 3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM