【问题标题】:How to access an array within one button_click, from a different button_click?如何从不同的 button_click 访问一个 button_click 内的数组?
【发布时间】:2021-12-09 04:41:30
【问题描述】:

当我点击“newRound”按钮时,程序会生成 Minor Arcana Deck 并通过 FisherYatesShuffle 方法对其进行洗牌。

public partial class MainWindow : Window
    {
     public MainWindow()
            {
                InitializeComponent();
            }
    
     private void newRound_Click(object sender, RoutedEventArgs e)
            {
                var minorArcanaDeck = new string[] {"Ace of Wands","Two of Wands", etc.};
                var rng = new Random();
                rng.Shuffle(minorArcanaDeck);
            }  
    }

static class FisherYatesShuffle
        {
            public static void Shuffle<T>(this Random rng, T[] array)
            {
                int n = array.Length;
                while (n > 1)
                {
                    int k = rng.Next(n--);
                    T temp = array[n];
                    array[n] = array[k];
                    array[k] = temp;
                }
            }
        }

在另一个按钮中(也在部分类中),我想访问这个小ArcanaDeck 数组,但我不知道如何。如何使下面的代码工作,以便在单击“drawCard”按钮时文本框显示数组的值?

private void drawCard_Click(object sender, RoutedEventArgs e)
    {
        myText.Text = minorArcanaDeck[0];  
   
    }

【问题讨论】:

  • 将minorArcanaDeck声明为类变量(方法外)

标签: c# wpf wpf-controls


【解决方案1】:

你需要了解局部变量和类变量(字段/属性)的区别

您应该将数组定义为一个字段,这样每个(非静态)方法都可以访问它。

public partial class MainWindow : Window
{
    // fields
    private string[] _minorArcanaDeck = new string[] {"Ace of Wands","Two of Wands", etc.};
    private Random _rng = rand = new Random(Guid.NewGuid().GetHashCode());

    public MainWindow()
    {
        InitializeComponent();
    }

    private void newRound_Click(object sender, RoutedEventArgs e)
    {
        _rng.Shuffle(_minorArcanaDeck);
    }  
    
    private void drawCard_Click(object sender, RoutedEventArgs e)
    {
        myText.Text = _minorArcanaDeck[0];  
    }
}

static class FisherYatesShuffle
{
    public static void Shuffle<T>(this Random rng, T[] array)
    {
        int n = array.Length;
        while (n > 1)
        {
            int k = rng.Next(n--);
            T temp = array[n];
            array[n] = array[k];
            array[k] = temp;
        }
    }
}

在我的例子中,我使用_ 前缀,所以我有一个明确的命名约定。但这不是必需的。 通过将 Random 移出 newRound_Click 方法并使用随机种子,将生成更好的随机数。 (否则你总是有相同的随机序列)

【讨论】:

  • 谢谢!!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-19
  • 2013-03-31
  • 1970-01-01
  • 2019-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多