列表中的随机访问项目 [英] Access random item in list
问题描述
我有一个ArrayList,我需要能够点击一个按钮,然后随机挑选出从该列表的字符串并显示它的一个消息。
我怎么会去这样做?
-
创建
随机
类某处的一个实例。请注意,这是pretty重要的是不要每次需要一个随机数的时间创建一个新的实例。您应该重新使用旧实例中生成的数字,以达到均匀。你可以有一个静态
字段地方(小心线程安全问题):静态随机RND =新的随机();
-
询问
随机
实例给你的最大的的ArrayList的项目数的随机数
:INT R = rnd.Next(list.Count);
-
显示字符串:
MessageBox.Show((字符串)列表[R]);
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.
How would I go about doing this?
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();
Ask the
Random
instance to give you a random number with the maximum of the number of items in theArrayList
:int r = rnd.Next(list.Count);
Display the string:
MessageBox.Show((string)list[r]);
这篇关于列表中的随机访问项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!