名单上的所有位置数据覆盖 [英] List overwriting data on all positions
问题描述
我创建了一个类3个字段:
I created a class with 3 fields:
class Gente
{
int _ID;
string _nome, _sexo;
public Gente()
{
_ID = 0;
_nome = "";
_sexo = "";
}
public int ID
{
set { _ID = value; }
get { return _ID; }
}
public string Nome
{
set { _nome = value; }
get { return _nome; }
}
public string Sexo
{
set { _sexo = value; }
get { return _sexo; }
}
}
然后,我宣布从类和列表。对象从该类这样我可以能够添加到列表
Then I declared a List from that class and an object from that class so that I can be able to add to the List.
List<Gente> Alunos = new List<Gente>();
Gente professor = new Gente();
我第一次做Alunos.Add(教授);到列表中它正确地将信息发送到0位置。
The first time I do the Alunos.Add(professor); to the list it correctly sends the information to the 0 position.
但是,当我做第二次它会覆盖新数据位置0的一切,除了添加新数据到一个新的位置,1。
But when I do it second time it overwrites everything on position 0 with the new data besides adding the new data to a new position, 1.
推荐答案
什么是您的代码,这两个对象添加到列表中的样子?我的猜测是:
What does your code to add the two objects to the list look like? My guess is:
Gente professor = new Gente();
professor.Nome = "Fu";
Alunos.Add(professor);
professor.Nome = "Bar";
Alunos.Add(professor);
这是不正确。当您添加引用类型列表,你只需要添加到原来的对象的引用。在这种情况下,你要添加两个引用同一个对象两次。
Which is incorrect. When you add reference types to a list, you're only adding a reference to the original object. In this case you're adding two references to the same object twice.
因此,当你修改的第二个对象...你还修改了第一位。
Therefore, when you modify the second object...you're also modifying the first.
一个简单的一行修复将重新初始化教授
第二次使用前:
A simple one-liner fix would be to re-initialize professor
before its second use:
Gente professor = new Gente();
professor.Nome = "Fu";
Alunos.Add(professor);
professor = new Gente();
professor.Nome = "Bar";
Alunos.Add(professor);
这篇关于名单上的所有位置数据覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!