列表替换所有先前的元素
本文关键字:元素 替换 列表 | 更新日期: 2023-09-27 18:16:44
我有一个Person类型的列表。当我创建人员列表时,它将用当前列表元素的信息替换前一个列表元素的信息。我读过关于这是静态类变量的问题,但我的属性都不是静态的。
class Person{
private string _name;
private string _address;
public string Name{
get{ return _name;}
set { _name = value;}
public string Address{
get{ return _address;}
set { _address = value;}
}
}
我从文件中读取人,并将其存储在字符串数组中。我检查了一下,确保数组是正确的。它是。
奇怪的是:
string[] personArray;
Person tempPerson = new Person();
List<Person> people = new List<Person>();
foreach (string line in lines)//lines are the people from file, it is correct
{
personArray = line.Split(',');
if (personArray.Length == 2)
{
tempPerson.Name = personArray[0];
tempPerson.Address = personArray[1];
people.Add(tempPerson);
}
}
我遍历代码,正确地添加了第一个人,添加了第二个人调查人们,他们都有第二个人的信息。在添加语句之前,一切看起来都很正常。
您需要移动
的初始化Person tempPerson = new Person();
进入循环
string[] personArray;
List<Person> people = new List<Person>();
foreach (string line in lines)//lines are the people from file, it is correct
{
personArray = line.Split(',');
if (personArray.Length == 2)
{
Person tempPerson = new Person();
tempPerson.Name = personArray[0];
tempPerson.Address = personArray[1];
people.Add(tempPerson);
}
}