【问题标题】:CS0029 C# Cannot implicitly convert type 'void' to 'System.EventHandler'CS0029 C# 无法将类型“void”隐式转换为“System.EventHandler”
【发布时间】:2019-05-06 09:55:40
【问题描述】:

返回错误

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

【问题讨论】:

  • UpdateScreen()执行UpdateScreenmethod 本身;正确的语法是gameTimer.Tick += UpdateScreen;。我们将Tick 分配给方法,而不是分配给方法的result(即void

标签: c#


【解决方案1】:

您应该分配不带括号的方法,因为您正在尝试分配方法的结果(由于void,它没有)

方法也必须有正确的参数。

gameTimer.Tick += UpdateScreen;

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

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

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

【讨论】:

    【解决方案2】:

    不需要括号。你也可以这样做:

    gameTimer.Tick += (s, ev) => { UpdateTimer(s, ev); }
    

    并修复 UpdateTimer 方法。

    或者您也可以执行以下操作:

    gameTimer.Tick += new EventHandler<object>(UpdateTimer);
    

    更多关于代表的信息:

    https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/delegates/

    这里有更多关于 DispatchTimer 的信息:

    https://docs.microsoft.com/en-us/uwp/api/Windows.UI.Xaml.DispatcherTimer#Windows_UI_Xaml_DispatcherTimer_Tick

    【讨论】:

    • 这个gameTimer.Tick += new EventHandler&lt;object&gt;(UpdateTimer); 不起作用。 UpdateTimer 不存在,UpdateScreen 没有对象作为参数,gameTimer.Tick += (s, ev) =&gt; { UpdateTimer(s, ev); } 同样的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-30
    • 1970-01-01
    • 2022-07-06
    • 2020-04-23
    • 2017-10-06
    • 2022-08-23
    相关资源
    最近更新 更多