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

Gjo*_*gji 6 c#

我想写一个C#程序,它以随机顺序执行几个方法A(),B()和C().我怎样才能做到这一点?

Tim*_*mwi 14

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

public static Random Rnd = new Random();
Run Code Online (Sandbox Code Playgroud)

让我们定义一个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;
}
Run Code Online (Sandbox Code Playgroud)

这个Shuffle实现由romkyns提供!

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

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

  • @Pauli:编写一个有时会输出垃圾的程序比一个可靠地运行垃圾的程序总是更容易. (3认同)