【问题标题】:C# GUI Dice Game pass by referenceC# GUI Dice Game 通过引用传递
【发布时间】:2016-02-09 12:08:56
【问题描述】:

好的,我正在尝试制作一个 GUI 骰子游戏,其中骰子数字显示在文本框中。

我必须创建一个代表骰子的类,并且我的至少一个方法必须通过引用正确传递参数。我的问题是我对类或传递参数不太熟悉

我收到一个错误 rd.RollDice1(参考骰子1); rd.RollDice2(参考骰子2); (我确定我没有错误地构造 RollDice 类) 请问有人可以帮我吗?

到目前为止,这是我的代码:

public partial class Form1 : Form
{
    private RollDice rd;


    public Form1()
    {
        InitializeComponent();
        rd = new RollDice();
    }

    private void button1_Click(object sender, EventArgs e)
    {  
        int dice1, dice2;

        const int EYE = 1;

         const int BOX = 6;

        rd.RollDice1(ref dice1);

        rd.RollDice2(ref dice2);

        string result = string.Format("{0}", dice1);
        string result2 = string.Format("(0)", dice2);

             textBox1.Text = result;

               textBox2.Text = result;

         if (dice1 == EYE && dice2 == BOX)
         {
             MessageBox.Show("You rolled a Snake Eyes!");

         }
        if (dice1 == BOX && dice2 == BOX)
        {

            MessageBox.Show("You rolled BoxCars!");

        }

        else
        {
            MessageBox.Show("You rolled a {0} and a {1}", dice1, dice2);
        }
    }
}

}

class RollDice
{

   const int EYE = 1;
   const int BOX = 6;

    public int RollDice1(ref int dieValue1)
    {
        Random randomNums = new Random();

         dieValue1 = randomNums.Next(1, 7);

        return dieValue1;

    }

    public int RollDice2(ref int dieValue2)
    {
        Random randomNums = new Random();

         dieValue2 = randomNums.Next(1, 7);

        return dieValue2;

    }






}

}

【问题讨论】:

  • "I get an error at..." - 错误是什么?另外,您为什么要通过引用传递 返回值?不妨选择两种方法中的一种。
  • 啊这就是为什么...我会得到回报并继续努力。谢谢!

标签: c# user-interface dice


【解决方案1】:

使用 ref 传递变量需要使用默认值初始化该变量。如果你没有用初始值设置两个骰子,你的编译器会抱怨"Use of unassigned local variable xxxxx"

private void button1_Click(object sender, EventArgs e)
{  

    const int EYE = 1;
    const int BOX = 6;

    int dice1 = EYE;
    int dice2 = BOX;

    rd.RollDice1(ref dice1);
    rd.RollDice2(ref dice2);

    .....

但是查看您的代码,无需使用 ref 传递该值,您可以简单地获取返回值

    dice1 = rd.RollDice1();
    dice2 = rd.RollDice2();

当然你应该改变你类中的两个方法来移除ref传递的参数

class RollDice
{
    Random randomNums = new Random();

    public int RollDice1()
    {
        return randomNums.Next(1, 7);
    }

    public int RollDice2()
    {
        return randomNums.Next(1, 7);
    }
}

【讨论】:

  • 我怎么没看到!?!?哈哈谢谢你这是完美的!
猜你喜欢
  • 2016-07-14
  • 2011-01-17
  • 2020-04-01
  • 2014-03-10
  • 2012-06-14
  • 2014-05-05
  • 2012-01-27
  • 2020-12-06
  • 1970-01-01
相关资源
最近更新 更多