方法以随机顺序调用(C#)

时间:2011-01-26 01:00:34

标签: c#

我想编写一个C#程序,它以随机顺序执行多个方法A(),B()和C()。我怎么能这样做?

1 个答案:

答案 0 :(得分:14)

假设一个随机数生成器声明如下:

public static Random Rnd = new Random();

让我们定义一个Shuffle函数,使列表按随机顺序排列:

/// <summary>
/// Brings the elements of the given list into a random order
/// </summary>
/// <typeparam name="T">Type of elements in the list.</typeparam>
/// <param name="list">List to shuffle.</param>
/// <returns>The list operated on.</returns>
public static IList<T> Shuffle<T>(this IList<T> list)
{
    if (list == null)
        throw new ArgumentNullException("list");
    for (int j = list.Count; j >= 1; j--)
    {
        int item = Rnd.Next(0, j);
        if (item < j - 1)
        {
            var t = list[item];
            list[item] = list[j - 1];
            list[j - 1] = t;
        }
    }
    return list;
}

这个Shuffle实现由romkyns提供!

现在只需将方法放入列表中,随机播放,然后运行它们:

var list = new List<Action> { A, B, C };
list.Shuffle();
list.ForEach(method => method());