Skip to main content
 首页 » 编程设计

c#之是否使用另一个列表复制值或引用初始化了通用列表

2024年02月05日15wayfarer

如果我有一个 List<T> Foo然后我初始化另一个 List<T> Bar通过 Foo到 Bar 的构造函数, 做 Bar可以访问 Foo 中的原始对象?或者是 Bar 中的对象单独的副本?

这是一个愚蠢的例子:

class Car 
{ 
    public string Make   { get; private set; } 
    public string Model  { get; private set; } 
    public string Year   { get; private set; } 
 
    public int FuelLevel { get; private set; } = 0; 
    public int OilLevel  { get; private set; } = 0; 
 
    public Car(string make, string model, string year) 
    { 
        Make = make; 
        Model = model; 
        Year = year; 
    } 
 
    public void Refuel() 
    { 
        FuelLevel = 100; 
    } 
} 
 
class Program 
{ 
    public static void Main(string[] args) 
    { 
        List<Car> CarsThatJoeOwns = new List<Car> { new Car("Ford", "Explorer", "2005"), 
                                                    new Car("Hyundai", "Elantra", "2011") }; 
 
        // For some reason, Paul owns the exact same types of cars that Joe owns... 
        List<Car> CarsThatPaulOwns = new List<Car> (CarsThatJoeOwns); 
 
        foreach (Car car in CarsThatPaulOwns) 
        { 
            car.Refuel(); // <---- does this affect the cars that Joe owns too? 
        } 
    } 
} 

请您参考如下方法:

类(class)Car是引用类型,因此,将发生以下情况:

var car = new Car("Ford", "Explorer", "2005"); 
var carReference = car; 
carReference.Refuel(); 
 
//Will have the value of 100, even if no method was called in the car 
//object, but because it is a reference type, calling Refuel method 
//on carReference will also affect to the variable referenced by 
//carReference (car) 
var fuelLevel = car.FuelLevel 

在您的代码示例中,您有以下特定部分:

List<Car> CarsThatJoeOwns = new List<Car> 
{ 
    new Car("Ford", "Explorer", "2005"), 
    new Car("Hyundai", "Elantra", "2011") 
}; 
 
// For some reason, Paul owns the exact same types of cars that Joe owns... 
List<Car> CarsThatPaulOwns = new List<Car> (CarsThatJoeOwns); 

List<T>分配 CarsThatPaulOwns 时调用的构造函数将现有列表 CarsThatJoeOwns 作为参数, 它实现了接口(interface) ICollection<T> , 所以 CarsThatJoeOwns可以转换为 ICollection<T> .

此外,请查看通用 List 的构造函数的源代码类:

public List(IEnumerable<T> collection) { 
    if (collection==null) 
        ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection); 
    Contract.EndContractBlock(); 
 
    ICollection<T> c = collection as ICollection<T>; 
    if( c != null) { 
        int count = c.Count; 
        if (count == 0) 
        { 
            _items = _emptyArray; 
        } 
        else { 
            _items = new T[count]; 
            c.CopyTo(_items, 0); 
            _size = count; 
        } 
    }     
    else {                 
        _size = 0; 
        _items = _emptyArray; 
        // This enumerable could be empty.  Let Add allocate a new array, if needed. 
        // Note it will also go to _defaultCapacity first, not 1, then 2, etc. 
 
        using(IEnumerator<T> en = collection.GetEnumerator()) { 
            while(en.MoveNext()) { 
                Add(en.Current);                                     
            } 
        } 
    } 
} 

因为 CarsThatJoeOwns可以转换为 ICollection<T> , 行 c.CopyTo(_items, 0);将被执行,它会执行以下操作(如 Microsoft Reference Source 中所示):

public void CopyTo(T[] array, int arrayIndex) { 
    // Delegate rest of error checking to Array.Copy. 
    Array.Copy(_items, 0, array, arrayIndex, _size); 
} 

并且,如 MSDN 文档中所述,Array.Copy将执行以下操作:

...Remarks...If sourceArray and destinationArray are both reference-type arrays or are both arrays of type Object, a shallow copy is performed. A shallow copy of an Array is a new Array containing references to the same elements as the original Array. The elements themselves or anything referenced by the elements are not copied. In contrast, a deep copy of an Array copies the elements and everything directly or indirectly referenced by the elements.

请注意“数组的浅拷贝是一个新数组,其中包含对与原始数组相同的元素的引用” 部分。简单地说,新列表CarsThatPaulOwns将保留对 CarsThatJoeOwns 中已存在对象的引用列表,以及 foreach循环定义:

foreach (Car car in CarsThatPaulOwns) 
{ 
    car.Refuel(); 
} 

也会影响 CarsThatJoeOwns 中的值列表。反之亦然(在 CarsThatJoeOwns 列表上调用 Refuel 方法也会影响 CarsThatPaulOwns 列表)。