random rd = new random();
int name = rd.Next(0,9);
if(name == 1 )
会发生一些事情
if(name == 2 )
会发生一些事情
if(name == 3 )
会发生一些事情
if(name == 4 )
会发生一些事情
if(name == 5 )
会发生一些事情
。
。
如何制作它不会重复?
答案 0 :(得分:1)
如果我理解你,你想以随机顺序调用所有动作;要做到这一点,创建动作,比如一个数组:
Action[] actions = new Action[] {
() => {Console.Write("I'm the first");},
() => {Console.Write("I'm the second");},
...
() => {Console.Write("I'm the tenth");},
};
然后 shuffle 集合(数组):
// simpelst, not thread safe
static Random generator = new Random();
...
int low = actions.GetLowerBound(0);
int high = actions.GetUpperBound(0);
for (int i = low; i < high; ++i) {
int index = i + generator.Next(high - i + 1);
var h = actions.GetValue(i);
actions.SetValue(actions.GetValue(index), i);
actions.SetValue(h, index);
}
最后,调用:
foreach (var action in actions)
action();
答案 1 :(得分:0)
正如一些评论中所建议的那样,您应该创建一个列表(或堆栈/队列,具体取决于您的确切实现),该列表随机排序&#34;。因此,举例来说,你可以这样做:
class Program
{
static void Main(string[] args)
{
List<int> allElements = new List<int>();
for (int i = 0; i <= 9; i++)
allElements.Add(i);
Random rnd = new Random();
Queue<int> myQueue = new Queue<int>(allElements.OrderBy(e => rnd.NextDouble()));
while (myQueue.Count > 0)
{
int currentInt = myQueue.Dequeue();
Console.WriteLine(currentInt);
}
Console.ReadLine();
}
}