我只是学习C#而无法在arraylist中显示随机对象。 代码如下`
ArrayList emp = new ArrayList();
hseEmployee e3 = new hseEmployee("Aine","Porter",5,26000);
hseEmployee e4 = new hseEmployee("Tara", "Standard", 2, 20000);
hseEmployee e5 = new hseEmployee("John", "Porter", 7, 28000);
hseEmployee e6 = new hseEmployee("Keith", "Porter", 3, 22000);
hseEmployee e7 = new hseEmployee("Aine", "Porter", 5, 26000);
emp.Add(e3);
emp.Add(e4);
emp.Add(e5);
emp.Add(e6);
emp.Add(e7);
Doctor d = new Doctor("Niamh","Doctor",5,40000);
Doctor d1 = new Doctor("Briege", "Doctor", 13, 100000);
Doctor d2 = new Doctor("Thomas", "Doctor", 9, 60000);
Doctor d3 = new Doctor("Ciara", "Doctor", 1, 30000);
Doctor d4 = new Doctor("Chris", "Doctor", 6, 50000);
emp.Add(d);
emp.Add(d1);
emp.Add(d2);
emp.Add(d3);
emp.Add(d4);
for (int i = 0; i <=10; i++)
{
Random r = new Random();
int index = r.Next(emp.Count);
richTextBox1.AppendText(emp[index].ToString());
}
答案 0 :(得分:2)
将Random放在for循环之外。
随机数生成从种子值开始。如果相同 种子被重复使用,生成相同的数字序列。一 产生不同序列的方法是制作种子价值 与时间有关,从而与每个新系列产生不同的系列 随机
的实例
当你在循环中有Random时,你正在使用相同的种子值调用Random的构造函数,因此你有相同的数字,而不是随机的。
Random r = new Random();
for (int i = 0; i <=10; i++)
{
int index = r.Next(emp.Count);
richTextBox1.AppendText(emp[index].ToString());
}