首页 > 解决方案 > C#:协助使这种 shuffle 方法工作

问题描述

我仔细Shuffle()研究了 C# 文档,但Shuffle()我还没有找到一个名为进行洗牌或随机化的实际逻辑。

这是我了解 Fisher-Yates 方法的地方,这使我找到了这篇特别的帖子,并提出了一个我喜欢手榴弹的解决方案:

随机化一个列表<T>

不幸的是,我似乎无法让这个解决方案为我工作。无论我如何配置它,我总是会遇到这个错误:

error CS1501: No overload for method 'Shuffle' takes '0' arguments如果我想以这种方式维护解决方案:

using System;
using System.Collections.Generic;

class Program
{
    public static void Main()
    {
        // List<Deck> deck = new List<Deck>();
        Deck deck = new Deck();
        deck.Shuffle();
        System.Console.WriteLine(deck);
    }
}

public class Deck {
   public List<Card> Cards = new List<Card>();

public Deck() {
  string[] ranks = { "Ace", "Two", "Three", "Four", "Five" };
  string[] suits = { "Diamonds", "Hearts", "Clubs", "Spades" };

  foreach (string suit in suits) {
      foreach (string rank in ranks) {
          Card card = new Card(rank, suit);
          Cards.Add(card);
      }
  }
}

  public override string ToString()
  {
      string s = "[";
      foreach (var card in Cards) {
        s += card.ToString() + ", ";
      }
      s += "]";
      return s;
  }

    private static Random rng = new Random();

    public static void Shuffle<T>(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;  
        }  
    }
}

public class Card {
    // properties
    public string suit { get; set; }
    public string rank { get; set; }

    public override string ToString()
    {
      return $"{rank} of {suit}"; 
    }

    public Card(string rank, string suit){
       //initializations
       this.rank = rank;
       this.suit = suit;
    }

}

它具有使用内置方法的外观和感觉,但是该错误告诉我我需要传递一些东西,Shuffle()因为我这样声明它:public static void Shuffle<T>(IList<T> list),无论我尝试传递什么,它都会导致另一个错误。

那么,如果我选择这个:

class Program
{
    public static void Main()
    {
        List<Deck> deck = new List<Deck>();
        // Deck deck = new Deck();
        deck.Shuffle();
        System.Console.WriteLine(deck);
    }
}

我被告知 Shuffle 不是一种方法: error CS1061: TypeSystem.Collections.Generic.List' 不包含Shuffle' and no extension methodShuffle' 类型的定义System.Collections.Generic.List<Deck>' could be found.

我知道这一点,但是这对手榴弹有什么作用?除了几年的经验之外,我还缺少什么?

标签: c#

解决方案


原型为Shuffle

public static void Shuffle<T>(IList<T> list)

与您呼入的方式不同main

deck.Shuffle();

这就是您收到CS1051错误的原因。首先修复该错误,然后它也会为您工作。


推荐阅读