阵列的所有索引返回相同的值 [英] Array returning same values for all indexes

查看:104
本文介绍了阵列的所有索引返回相同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个叫做参与者的对象。
现在我想有我的参加对象的数组,这样我可以让他们在一个数据网格。

I created an object called Participant. Now I want to have an array of my Participant objects so that I could show them in a datagrid.

下面是codeS我试图(为更好地理解这一问题,我删除了循环和数据网格codeS):

Here are the codes I tried (for better understanding of the problem, I removed the loops and datagrid codes):

Participant[] list = new Participant[count];
Participant one = new Participant(name, address);
Participant two = new Participant(name2, address2);

list[0] = one;
list[1] = two;

然而,当我通过这种方式一个消息得到这样一个参与者的价值观,

However, when I get values of one participant like through a messagebox in this manner,

MessageBox.Show(list[0].getName());

这一切都反映了参与者的两个数据。同样是真实的,如果我有3个对象,所有它反映的是过去的数据发送到数组。

all it reflects are the data of participant two. Same is true if I have 3 objects, all it reflects is the data last sent into the array.

我知道这是可能有对象数组所以一定有什么东西我做错了。还是有更好的方式来做到这一点?

I know it is possible to have array of objects so there must be something I'm doing wrong. Or is there a better way to do this?

推荐答案

随着code为presented,我能想到引起了的唯一途径是,如果backig字段(参与者)被宣布为静态。如果是这样,去掉静态

With the code as presented, the only way I can think of causing that is if the backig field (in Participant) was declared "static". If so, remove the "static".

否则;执行实际的code做了为两个对象?抑或是将其添加到阵列后,覆盖的对象? (这意味着你在阵列中具有相同的对象两次)。

Otherwise; does the actual code do a "new" for the two objects? Or does it overwrite an object after adding it to the array? (which means you have the same object twice in the array).

我希望的ReferenceEquals(名单[0],列表[1])来是一个理智的世界虚假的 - 可以在测试此,让我们知道

I would expect ReferenceEquals(list[0], list[1]) to be false in a sane world - can you test this and let us know?

最后的思想;有没有在现实code的foreach ?这可能是臭名昭著的捕获变量的问题 ...

Final thought; is there a "foreach" in the real code? It could be the infamous captured variable problem...

这篇关于阵列的所有索引返回相同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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