C# 如何使属性赋值在循环中独立
本文关键字:循环 独立 赋值 何使 属性 | 更新日期: 2023-09-27 17:56:11
我不确定我的标题是否足够清晰或具体,但这就是我要做的。
我有新课程
public class Segments
{
public List<double> List1 { get; set; }
public List<double> List2 { get; set; }
public List<double> List3 { get; set; }
public List<double> List4 { get; set; }
}
public static void SplitSegments(CsvClass longList, List<Segments> segments)
{
Segments tempSegments = new Segments();
List<double> list1 = new List<double>();
List<double> list2 = new List<double>();
List<double> list3 = new List<double>();
List<double> list4 = new List<double>();
// Nested For loop that goes through a longList with its own properties.
// Below is a flag for when to split that longList.properties into segments
if (flag == true)
{
//The lists are now complete for the first segment.
list1.Add(longList.one[i]);
list2.Add(longList.two[i]);
list3.Add(longList.three[i]);
list4.Add(longList.four[i]);
//created a copy of the class properties
tempSegments.List1 = new List<double>(list1);
tempSegments.List2 = new List<double>(list2);
tempSegments.List3 = new List<double>(list3);
tempSegments.List4 = new List<double>(list4);
//Add to List<Segments>
segments.Add(tempSegments)
//Clear lists in order to move on to creating next segment of the longList.
list1.Clear();
list2.Clear();
list3.Clear();
list4.Clear();
break;
}
}
}
我的问题是,当创建新段并将其添加到List<Segments>
时,所有段都成为新段的相同副本。
我想类中的列表仍然引用与列表相同的对象。我的问题是,当新段添加到List<Segments>
时,它们不会删除旧段,我该如何做到这一点?
你应该移动这条线
Segments tempSegments = new Segments();
进入循环的主体,可能就在if
子句内 if (flag == true)
.这将在每次迭代时创建一个新段。
代码的整个部分如下所示:
if (flag == true)
{
Segments tempSegments = new Segments();
//The lists are now complete for the first segment.
list1.Add(longList.one[i]);
list2.Add(longList.two[i]);
list3.Add(longList.three[i]);
list4.Add(longList.four[i]);
//created a copy of the class properties
tempSegments.List1 = new List<double>(list1);
tempSegments.List2 = new List<double>(list2);
tempSegments.List3 = new List<double>(list3);
tempSegments.List4 = new List<double>(list4);
//Add to List<Segments>
segments.Add(tempSegments)
//Clear lists...
list1.Clear();
list2.Clear();
list3.Clear();
list4.Clear();
break;
}
//created a copy of the class properties
tempSegments = new Segments(); // otherwise you are just changing the properties on a single obj and adding that obj many times to your list.
tempSegments.List1 = new List<double>(list1);
tempSegments.List2 = new List<double>(list2);
tempSegments.List3 = new List<double>(list3);
tempSegments.List4 = new List<double>(list4);