C#WinForms序列不包含任何元素
如果删除前4行,则没有错误。 但有必要清理重量和形状。 这四条线怎么了C#WinForms序列不包含任何元素,c#,c,winforms,C#,C,Winforms,如果删除前4行,则没有错误。 但有必要清理重量和形状。 这四条线怎么了 public void GameOver() { this.Controls.Remove(pipeTop.First().PB); this.Controls.Remove(pipeBottom.First().PB); pipeTop.Remove(pipeTop.First()); pipeBottom.
public void GameOver()
{
this.Controls.Remove(pipeTop.First().PB);
this.Controls.Remove(pipeBottom.First().PB);
pipeTop.Remove(pipeTop.First());
pipeBottom.Remove(pipeBottom.First());
this.Controls.Remove(bird.PB);
this.Controls.Remove(ScoreBox);
splashScreen.Image = fm.getCapture("gameover");
splashScreen.Location = new Point(0, -500);
startButton.Location = new Point(startButtonPozitionX, this.Size.Height + 150);
statsButton.Location = new Point(statsButtonPozitionX, this.Size.Height + 150);
this.Controls.Add(startButton);
this.Controls.Add(statsButton);
this.Controls.Add(splashScreen);
GameOverAnimation.Start();
}
如果序列或集合没有元素,则使用First()生成异常,因此需要使用FirstOrDefault并检查返回值是否为!=在使用它之前为null
所以
1-将第一行替换为:
var topPipe = pipeTop.FirstOrDefault();
if (firstPipe != null)
{
this.Controls.Remove(firstPipe.PB);
}
var bottomPipe = pipeBottom.FirstOrDefault();
if (bottomPipe != null)
{
this.Controls.Remove(bottomPipe.PB);
}
2-将第二行替换为:
var topPipe = pipeTop.FirstOrDefault();
if (firstPipe != null)
{
this.Controls.Remove(firstPipe.PB);
}
var bottomPipe = pipeBottom.FirstOrDefault();
if (bottomPipe != null)
{
this.Controls.Remove(bottomPipe.PB);
}
等等……一般来说,在不需要的地方加前缀
是不好的。