簡體   English   中英

在C#中的列表內修改列表

[英]Modifying list inside list in C#

我試圖通過迭代列表來修改內部列表中的值。 但是,無論外部列表如何,我對於內部列表都會得到相同的結果。 我預計maxSpeed的結果對於不同的車輛會有所不同。

希望有人可以對此提供幫助。

請注意,這不是隨機數生成器問題。 這只是我產生的示例代碼,而在不使用隨機數生成器的情況下,此問題確實存在於我的項目代碼中。

在這里運行C#代碼

List<Vehicle> mainList = new List<Vehicle>();
List<Properties> defaultPropertyList = new List<Properties>{
    new Properties() { maxSpeed = 0, isTwoDoor = true },
    new Properties() { maxSpeed = 0, isTwoDoor = true },
};


mainList.Add(
    new Vehicle() {
        number = 1,
        property = new List<Properties>(defaultPropertyList)
    }
);
mainList.Add(
    new Vehicle() {
        number = 2,
        property = new List<Properties>(defaultPropertyList)
    }
);           

foreach(Vehicle vehicle in mainList) {
    Random rnd = new Random();
    vehicle.property.ForEach(x => x.maxSpeed =  rnd.Next(1, 100));
}

問題在於,當您為每輛車初始化property字段時,您將添加對相同的兩個Properties對象(在頂部定義)的引用。 因此它們存在於所有車輛中,並且當您修改一個時,在兩個地方都對其進行了修改(因為它是相同的參考)。

初始化新載具時,您將需要在defaultPropertyList對象的副本。 然后它們將獨立存在。

一種方法:為Vehicle構造一個新的構造函數,該構造函數采用默認屬性,然后將其復制到那里。

public Vehicle(List<Properties> defaultProps) 
{
  property = new List<Properties>();
  foreach (var p in defaultProps)
  {
    var newProp = new Properties {
                                    maxSpeed = p.maxSpeed,
                                    isTwoDoor = p.isTwoDoor
                                    // add any other properties here
                                 };
    property.Add(newProp);
  }
}

defaultPropertyList只是一個包含一組項目的列表。 每個Vehicle具有相同的List<Properties>實例。 有沒有每Vehicle 只有一個,他們都在共享它。 這就是為什么無論您如何更改屬性,它們都具有相同的屬性。

要解決此問題,請不要創建一個共享。 只需創建所需的數量即可。 也許不是你,但是當我剛開始的時候,我害怕創建很多對象,並認為我可以通過創建盡可能少的對象來進行優化。

的確,我們不想不必要地創建許多昂貴的對象,但不必為此小氣。 根據需要創建多個。 例如,在Web應用程序中,僅跟蹤單個請求就不可能跟蹤創建了多少個對象。

您可以這樣做:

Random rnd = new Random(); // Despite what I just said,
                           // you only need one of these this time.
foreach(Vehicle vehicle in mainList) {        
    vehicle.property = new List<Properties>{
        new Properties() { maxSpeed = rnd.Next(1, 100), isTwoDoor = true },
        new Properties() { maxSpeed = rnd.Next(1, 100), isTwoDoor = true },
}

暫無
暫無

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

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