如何访问列表中的随机项目? [英] How to access random item in list?
问题描述
我有一个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.
我该怎么做?
推荐答案
-
在某处创建
Random
类的实例.请注意,每次需要随机数时都不要创建新实例,这一点非常重要.您应该重用旧实例,以实现生成数字的统一性.您可以在某处有一个static
字段(请注意线程安全性问题):
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 astatic
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屋!