我正在为学校做一个tictactoe项目,我似乎无法解决我无法访问的代码问题。我查找了其他无法访问的代码问题,但我不确定如何解决它,因为我不是很擅长这个。我知道这是一个警告,但当我开始我的程序时,它不会填写空白当我按他们。
private void Movement(object sender, EventArgs e)
{
if (InvokeRequired)
{
this.Invoke(new Action<object, EventArgs>(Movement), new object[] { sender, e });
return;
UpdateData(sender); //This is where it points for unreachable
var lbl = (Label)sender;
lbl.Enabled = false;
lbl.Text = currentPlayer.ToString();
if (!CheckWin())
NextTurn();
}
}
private void UpdateData(object sender)
{
Label lbl = sender as Label;
if (lbl == lbl00)
GameData[0, 0] = currentPlayer;
else if (lbl == lbl10)
GameData[1, 0] = currentPlayer;
else if (lbl == lbl20)
GameData[2, 0] = currentPlayer;
else if (lbl == lbl01)
GameData[0,1] = currentPlayer;
else if (lbl == lbl11)
GameData[1, 1] = currentPlayer;
else if (lbl == lbl21)
GameData[2, 1] = currentPlayer;
else if (lbl == lbl02)
GameData[0, 2] = currentPlayer;
else if (lbl == lbl12)
GameData[1, 2] = currentPlayer;
else if (lbl == lbl22)
GameData[2, 2] = currentPlayer;
}
答案 0 :(得分:5)
因为您在return
行之后加this.Invoke(new Action<object, EventArgs>(Movement), new object[] { sender, e });
所以其他行无法访问
答案 1 :(得分:1)
只是为了添加更明显的答案,您还没有正确实现"Invoke on UI Thread"模式。您需要使用额外的else
分支替换返回:
private void Movement(object sender, EventArgs e)
{
if (InvokeRequired)
{
// Oops, we're not on the UI thread. Invoke on the UI thread.
this.Invoke(new Action<object, EventArgs>(Movement), new object[] { sender, e });
... nasty exceptions happen if you try and update UI controls on a non-UI thread
}
else
{
// Now we're on the UI thread
UpdateData(sender);
... clear to interact with UI controls.
}
}
虽然你也可以使用return
重构代码以尽早退出非UI线程分支,然后删除else
。
private void Movement(object sender, EventArgs e)
{
if (InvokeRequired)
{
// Oops, we're not on the UI thread. Invoke on the UI thread.
this.Invoke(new Action<object, EventArgs>(Movement), new object[] { sender, e });
return; // i.e. exit the method here from this non UI thread branch
}
// We are now on the UI thread ...
UpdateData(sender);
...
}