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

vin*_*sty 0 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));
}
Run Code Online (Sandbox Code Playgroud)

Yaa*_*lis 5

问题是,当您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);
  }
}
Run Code Online (Sandbox Code Playgroud)