【发布时间】:2017-10-21 16:47:36
【问题描述】:
所以我正在尝试做一个随机提示生成器,很明显,至少在所有提示都被看到之前不应该显示相同的提示
private string getRandomTip()
{
List<string> Titles = new List<string> {
"You can copy the result by clicking over it",
"Remember to press Ctrl + Z if you messed up",
"Check web.com to update the app"};
Random rnd = new Random();
int Index = rnd.Next(0, Titles.Count);
string randomString = Titles[Index];
Titles.RemoveAt(Index);
return randomString;
}
但由于某种原因,这会连续两次或多次重复提示。我认为我可以生成随机数,直到我得到一个不是最后一个的,但这看起来像是一个糟糕的优化代码。
你能帮帮我吗?
编辑:好的,非常感谢你们,我现在正在尝试这个
public List<string> Titles = new List<string> {
"You can copy the result by clicking over it",
"This calculator was created by Glow on 21/10/17",
"Click on this tip to show the next one"};
private string getRandomTip()
{
string randomString;
if (Titles.Count > 0) {
Random rnd = new Random();
int Index = rnd.Next(0, Titles.Count);
randomString = Titles[Index];
Titles.RemoveAt(Index);
}
else
{
randomString = "Those were all the tips!";
}
return randomString;
}
而且效果很好。再次感谢:)
【问题讨论】:
-
每次调用该方法时,列表都会重新初始化。从此临时列表中删除不会影响下次通话时发生的任何事情。它将再次充满所有这些。您需要将列表存储在方法之外。
-
推荐你read the documentation。使用默认构造函数(相同的种子)创建一个新的随机数将创建相同的随机数序列。第 1 节的第 3 段将引导您朝着正确的方向前进。
-
是的,非常感谢你,我已经更新了它,看起来它现在可以工作了。谢谢:)
-
如果重复还不够……随机数不能是唯一的,但它不会阻止人们尝试-bing.com/search?q=c%23+random+unique+numbers