我知道这个问题的一个版本会经常被问到,但是我在最后几天查看论坛并尝试实施Fisher-Yates shuffle,但我没有设法做到这一点,因为我总是得到一个错误,因为它不将Shuffle作为一个函数并且给出了这个错误: Entscheidungsfragen.Shuffle(this System.Collections.Generic.IList)':扩展方法必须在非泛型静态类中定义。
private static System.Random rng = new System.Random();
public static void Shuffle<T>(this IList<T> list)
{
int n = list.Count;
while (n > 1) {
n--;
int k = rng.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
private static void CreateList(string[] args)
{
var scenes =new List<Action>(szene1, szene2);
scenes.Shuffle ();
foreach (Action sce in scenes)
sce ();
}
我真的很感激,如果有人可以帮助我,因为我只是迷失了因为我尝试了我发现的一切。
答案 0 :(得分:3)
错误说明了。将扩展方法Shuffle
移动到非泛型静态类中,如下所示:
public static class ListExtensions
{
private static System.Random rng = new System.Random();
public static void Shuffle<T>(this IList<T> list)
{
int n = list.Count;
while (n > 1) {
n--;
int k = rng.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
}
答案 1 :(得分:0)
这是一个扩展类
public static class ExtensionClass
{
private static System.Random rng = new System.Random();
public static void Shuffle<T>(this IList<T> list)
{
int n = list.Count;
while (n > 1)
{
n--;
int k = rng.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
}