2017-07-26 82 views
-1

我知道這個問題prob的版本被問得很頻繁,但我調查了最後幾天的論壇,並試圖實施Fisher-Yates shuffle,但我沒有設法做到這一點因爲我總是得到一個錯誤,因爲它沒有把Shuffle作爲一個函數並給出這個錯誤:Entscheidungsfragen.Shuffle(this System.Collections.Generic.IList)':擴展方法必須在非泛型靜態類中定義。c#randomize列表<action>

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(); 
} 

我倒是很感激,如果有人可以幫助我,因爲i'm只是失去了事業,我什麼都試過,我發現。

+0

其中包含了'Shuffle'擴展方法必須是靜態的類,它必須是可從'CreateList'訪問。 –

回答

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; 
     } 
    } 
} 
+0

非常感謝你,現在我覺得這麼愚蠢,花了這麼多時間來解決它:D – Boernie

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