如何访问列表中的随机项目? [英] How to access random item in list?

查看:60
本文介绍了如何访问列表中的随机项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ArrayList,我需要能够单击一个按钮,然后从该列表中随机选择一个字符串,并将其显示在消息框中.

I have an ArrayList, and I need to be able to click a button and then randomly pick out a string from that list and display it in a messagebox.

我该怎么做?

推荐答案

  1. 在某处创建Random类的实例.请注意,每次需要随机数时都不要创建新实例,这一点非常重要.您应该重用旧实例,以实现生成数字的统一性.您可以在某处有一个static字段(请注意线程安全性问题):

  1. Create an instance of Random class somewhere. Note that it's pretty important not to create a new instance each time you need a random number. You should reuse the old instance to achieve uniformity in the generated numbers. You can have a static field somewhere (be careful about thread safety issues):

static Random rnd = new Random();

  • 询问Random实例可为您提供一个随机数,其中包含ArrayList中的最大项目数:

  • Ask the Random instance to give you a random number with the maximum of the number of items in the ArrayList:

    int r = rnd.Next(list.Count);
    

  • 显示字符串:

  • Display the string:

    MessageBox.Show((string)list[r]);
    

  • 这篇关于如何访问列表中的随机项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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