开发者

Methods call in random order (C#)

I want to write a C# program that executes several methods A(), B() and C() i开发者_如何学Pythonn random order. How can I do that?


Assuming a random number generator declared like this:

public static Random Rnd = new Random();

Let’s define a Shuffle function to bring a list into random order:

/// <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;
}

This Shuffle implementation courtesy of romkyns!

Now simply put the methods in a list, shuffle, then run them:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜