这段代码没有给我我期望的结果。
经过一番研究,我发现在循环中使用委托时,您必须捕获计数器的值——如通过inneri
and所见innerj
。但是,由于某种原因,我for
的 j 循环,
字符串stringThisRoll
只有掷骰子的前两个数字。
我似乎无法弄清楚为什么会这样。给出的intThisRoll
数字与应掷骰子的数量正确,但stringThisRoll
并没有全部。
我在stackoverflow上查看了其他一些问题,但似乎没有一个可以解决这个问题,只是需要捕获计数器。
谢谢
这是我的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Better_Betrayal_Dice_Roller
{
public partial class Form1 : Form
{
TextBox txtBox = new TextBox();
List<Button> buttons = new List<Button>();
List<Label> labels = new List<Label>();
public Form1()
{
int NumberOfOptions = 9;
/*Makes the controls*/
for (int i = 0; i < NumberOfOptions; i++)
{
Button tmpButton = new Button();
Label tmpLabel = new Label();
buttons.Add(tmpButton);
labels.Add(tmpLabel);
}
/*Add the controls to the form*/
for (int i = 0; i < NumberOfOptions; i++)
{
buttons[i].Visible = true;
labels[i].Visible = true;
buttons[i].Text = "Roll " + (i + 1).ToString();
labels[i].Text = "Please Roll";
buttons[i].Location = new Point(10, (30 * i) + 10);
labels[i].Location = new Point(100, (30 * i) + 15);
labels[i].Size = new Size(100, 20);
this.Controls.Add(buttons[i]);
this.Controls.Add(labels[i]);
}
/*delegates for the buttons*/
for (int i = 0; i < NumberOfOptions; i++)
{
int inneri = i;
int numberOfDice = inneri + 1;
buttons[i].Click += delegate(Object send, EventArgs e)
{
labels[inneri].Text = "";
string stringThisRoll = "";
int intThisRoll = 0;
var tempResults = diceResults(inneri+1);
for (int j = 0; j < tempResults.Count; j++)
{
int innerj = j;
intThisRoll += tempResults[innerj];
stringThisRoll += tempResults[innerj].ToString() + " ";
}
labels[inneri].Text = intThisRoll.ToString();
labels[inneri].Text += " Made of: " + stringThisRoll;
//MessageBox.Show(inneri.ToString());
//labels[inneri].Text += "Last one: " + tempResults[tempResults.Count-1].ToString();
};
}
InitializeComponent();
}
List<int> diceResults(int numDice)
{
Random rnd = new Random();
List<int> resultList = new List<int>();
int total = 0;
for (int i = 0; i < numDice; i++)
{
resultList.Add(rnd.Next(0, 3));
}
return resultList;
}
}
}