列出替换所有以前的元素 [英] list replacing all previous elements

查看:46
本文介绍了列出替换所有以前的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Person类型的列表.当我创建人员列表时,它会将前一个列表元素的信息替换为当前列表元素的信息.我已经读到这是静态类变量的问题,但是我的属性都不是静态的.

I have a list of type Person. When I create the list of people it replaces the previous list element's information with the current one. I have read about this being the problem with static class variables but none of my attributes are static.

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;}
}
}

我从文件中读取人员并将其存储在字符串数组中.我逐步检查以确保数组正确.是的.

I read in the people from a file and store it in a array of string. I stepped through to make sure the array is correct. It is.

在这里很奇怪:

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);
}
}

我逐步执行代码,并正确添加了第一个人,添加了第二个人 调查人员,他们都拥有第二人称的信息.一切正常,直到添加语句之后.

I step through the code and the first person is added properly, the second person is added look into people and they both have the second person's information. Everything looks right until after the add statement.

推荐答案

您需要移动

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);
          }
        }

否则,您将更改同一对象的属性.

Otherwise you are changing the properties of the same object.

这篇关于列出替换所有以前的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆