1

我试图随机化一个列表,然后把它放到一个图片框中。当我这样做时,我收到错误消息“索引超出范围。必须是非负数并且小于集合的大小”

这是随机的代码:

public class Dealer
{
    public static Random rand = new Random();
    public static List<Kort> KortenÄrBlandade = new List<Kort>();
    public void Shuffle()
    {
        List<Kort> KortenÄrBlandade = new List<Kort>(deckOfCards.OrderBy(_ => rand.Next(0, deckOfCards.Count)));
    }
}

这是调用该方法的代码

private void button1_Click(object sender, EventArgs e)
{
    Spelare.Dealer deal = new Spelare.Dealer();
    deal.Shuffle();
    pictureBox1.Image = Spelare.Dealer.KortenÄrBlandade[2].img;
}
4

3 回答 3

3

You can try using Fisher-Yates shuffle algorithm

http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle

It could be something like that:

public class Dealer {

  // Fisher-Yates shuffle algorithm with explicit generator
  private static void CoreShuffle(IList<Kort> list, Random generator) {
    if (Object.ReferenceEquals(null, list))
      throw new ArgumentNullException("list");
    else if (Object.ReferenceEquals(null, generator))
      throw new ArgumentNullException("generator");

    for (int i = list.Count - 1; i >= 0; --i) {
      int index = generator.Next(i + 1);

      Kurt h = list[index];
      list[index] = list[i];
      list[i] = h;
    }  
  }

  public static Random rand = new Random(); // <- Be careful: Random is not thread safe; readonly is also a good addition here

  // Return new shuffled list based on deckOfCards      
  public List<Kort> ShuffledList() {
    List<Kort> result = new List<Kort>(deckOfCards); // <- Check this line in your code
    CoreShuffle(result, rand);

    return result;   
  }
于 2013-10-04T13:29:31.743 回答
3

您的Shuffle方法不会打乱静态列表,而是创建(并忘记)该方法的本地变量。因此,您Spelare.Dealer.KortenÄrBlandade永远不会设置为任何真正的卡片列表。这意味着索引 2 不存在,这就是错误消息所说的。

附带说明:您的静态卡片列表+实例 Shuffle 方法的组合有点奇怪......

于 2013-10-04T13:31:52.440 回答
2
public void Shuffle()
{
    List<Kort> KortenÄrBlandade = new List<Kort>(...);
}

Shuffle 方法使用与 Dealer.KortenÄrBlandade 同名的局部变量。所以在方法返回后,你仍然有一个空列表。使固定:

public void Shuffle()
{
    Dealer.KortenÄrBlandade = new List<Kort>(...);
}

请注意,这不是正确的 shuffle。类设计也不正确,Shuffle() 应该是静态的,或者 KortenÄrBlandade 不应该是静态的。关于变量存储的困惑是您最终编写此错误的方式。

于 2013-10-04T13:33:22.383 回答