把我的代码放入方法中

时间:2016-10-18 11:30:46

标签: c# methods

我有完整的代码,但它很长,我相信它可以放入方法,我不知道如何做方法,如果有人可以帮助我把它放入一个方法,将不胜感激,谢谢

private void btnGenerate_Click(object sender, EventArgs e)
{
    Random rnd = new Random(); //this string is what is used to generate a random number
    int lottery = 0; //an integer named lottery. It is set to 0 since the program doesn't so it can initialise as any random number



    for (int i = 0; i <= 49; i++)
    {
        lottery = rnd.Next(1, 49);
        lblLot1.Text = lottery.ToString();
    }

    for (int i = 0; i <= 49; i++)
    {
        lottery = rnd.Next(1, 49);
        lblLot2.Text = lottery.ToString();
    }

    for (int i = 0; i <= 49; i++)
    {
        lottery = rnd.Next(1, 49);
        lblLot3.Text = lottery.ToString();
    }

    for (int i = 0; i <= 49; i++)
    {
        lottery = rnd.Next(1, 49);
        lblLot4.Text = lottery.ToString();
    }

    for (int i = 0; i <= 49; i++)
    {
        lottery = rnd.Next(1, 49);
        lblLot5.Text = lottery.ToString();
    }

    for (int i = 0; i <= 49; i++)
    {
        lottery = rnd.Next(1, 49);
        lblLot6.Text = lottery.ToString();
    }
}

2 个答案:

答案 0 :(得分:3)

每个标签都不需要方法。只需一个for循环就可以了:

foreach (Label lblLot in new Label[] {lblLot1, lblLot2, lblLot3, lblLot4, lblLot5, ...} )
{
    for (int i = 0; i <= 49; i++)
    {
        int lottery = rnd.Next(1, 49);
        lblLot.Text = lottery.ToString();
    }
}

另外,for循环对我来说似乎很奇怪。您想要一次,右边设置标签的值。如果你想每X秒更换一次,你需要一段时间左右。它不会冻结应用程序,直到它经过for循环50次,然后在屏幕上显示最后一个值。

所以我猜这应该做:

foreach (Label lblLot in new Label[] {lblLot1, lblLot2, lblLot3, lblLot4, lblLot5, ...} )
{
    int lottery = rnd.Next(1, 49);
    lblLot.Text = lottery.ToString();
}

答案 1 :(得分:1)

很抱歉,但您的代码非常奇怪。为什么要设置TextBox次49次的值?只有最后值才会显示!

所以这就是你可能想要做的事情(49个中的6个):

Random random = new Random();
int[] lottery = Enumerable.Range(1, 49).OrderBy(i => r.Next()).Take(6).ToArray();
lblLot1.Text = lottery[0].ToString();
lblLot2.Text = lottery[1].ToString();
lblLot3.Text = lottery[2].ToString();
lblLot4.Text = lottery[3].ToString();
lblLot5.Text = lottery[4].ToString();
lblLot6.Text = lottery[5].ToString();
  • Enumerable.Range()创建一系列从6到49的数字。
  • 此序列由OrderBy使用随机数
  • 进行混洗
  • 然后从该序列中的前六个数字创建一个数组
  • 最后文本框中填充了这六个值

通过创建一个混洗序列并获取前六个序列,可以避免重复。在您的代码中,您可以提出1, 17, 17, 19, 29, 35,这不是有效的彩票号码序列。

如果您希望对数字进行排序,则可以在OrderBy(i => i)Take(6)之间添加ToArray()。因此,只有所选择的六个再次排序:

int[] lottery = Enumerable.Range(1, 49).OrderBy(i => r.Next()).Take(6).OrderBy(i => i).ToArray();