我有一个应用程序,我需要将数据库中的数据填充到4个标签上,我希望这些标签出现在随机位置x但是在以下位置x:79,199,437,319。
我尝试使用Random
类但偶尔会返回相同的位置。有人有解决方案吗?每次运行应用程序时,我都希望answer1 - 回答4以随机播放位置。
answer1.Location = new Point(79, 60);
answer2.Location = new Point(199, 60);
answer4.Location = new Point(437, 60);
answer3.Location = new Point(319, 60);
答案 0 :(得分:2)
您可以将积分放在List<Point>
:
var list = new List<Point>
{
new Point(79, 60),
new Point(199, 60),
new Point(319, 60),
new Point(437, 60)
};
然后,您使用Fisher-Yates algorithm
对其进行随机播放var rand = new Random();
var n = list.Count - 1;
for(var n = list.Count; n > 0; n--)
{
int k = rng.Next(n - 1);
var value = list[k];
list[k] = list[n];
list[n] = value;
}
然后你使用:
answer1.Location = list[0];
answer2.Location = list[1];
answer3.Location = list[2];
answer4.Location = list[3];
答案 1 :(得分:0)
我认为你的用法是假的。
正确使用Random class是:
实例化课程
Random rnd1 = new Random();
比访问“randome”函数获取randome数字:
var yourrand = Random.Next(437 /*The maximum*/);