如何访问列表中的随机项目? [英] 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屋!