如何在c#中显示一个随机对象

本文关键字:一个 随机 对象 显示 | 更新日期: 2023-09-27 18:17:34

我刚刚学习c#,不能在数组列表中显示随机对象。代码如下'

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

如何在c#中显示一个随机对象

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