C# CS0029错误:无法将类型“void”隐式转换为“System.EventHandler”。

5

返回一个错误。

CS0029
C# 无法隐式将类型 'void' 转换为 'System.EventHandler'

该函数被用在这里:

gameTimer.Tick += UpdateScreen();

该函数的作用是:

private void UpdateScreen()
{
    if(Settings.GameOver == true)
    {
        if (Input.KeyPressed(Keys.Enter))
        {
            StartGame();
        }
    }
    else
    {
        if (Input.KeyPressed(Keys.Right) && Settings.direction != Direction.Left)
            Settings.direction = Direction.Right;
        else if (Input.KeyPressed(Keys.Left) && Settings.direction != Direction.Right)
            Settings.direction = Direction.Left;
        else if (Input.KeyPressed(Keys.Up) && Settings.direction != Direction.Down)
            Settings.direction = Direction.Up;
        else if (Input.KeyPressed(Keys.Down) && Settings.direction != Direction.Up)
            Settings.direction = Direction.Down;

        MovePlayer();
    }

    pbCanvas.Invalidate();
}

3
UpdateScreen是方法本身时,执行UpdateScreen();正确的语法是 gameTimer.Tick += UpdateScreen;。我们将Tick分配给该方法,而不是方法的结果(即void)。 - Dmitry Bychenko
2个回答

14

你应该不带括号地分配方法,因为你试图分配方法的结果(由于 void),它没有结果。

此外,该方法必须具有正确的参数。

gameTimer.Tick += UpdateScreen;

private void UpdateScreen(object sender, EventArgs e)
{
    // ...
}

或者如果您不想更改方法参数,您可以使用lambda表达式。(它创建一个新的委托,调用UpdateScreen方法。(wrapper))


gameTicker.Tick += (s, ee) => UpdateScreen();

3

这个 gameTimer.Tick += new EventHandler<object>(UpdateTimer); 不起作用。UpdateTimer 不存在,而且 UpdateScreen 没有一个对象作为参数,gameTimer.Tick += (s, ev) => { UpdateTimer(s, ev); } 同样存在问题。 - Jeroen van Langen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接