Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/80.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#WinForms序列不包含任何元素_C#_C_Winforms - Fatal编程技术网

C#WinForms序列不包含任何元素

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.

如果删除前4行,则没有错误。 但有必要清理重量和形状。 这四条线怎么了

 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);
}

等等……

一般来说,在不需要的地方加前缀
是不好的。