无法转换方法组

Cannot convert method group

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

然后像这样在 if 中使用它

if (blokace)

但是我得到一个编译器错误,"Cannot convert method group 'blokace' to non-delegate type 'bool'. Did you intend to invoke this method?"

有人可以帮我吗?一直都是这样,还行,不知道现在是什么问题

你就是做不到

if(blokace)

因为 blokace 不是一个布尔表达式,是一个方法

可以

if(blokace())

当且仅当方法 returns 一个布尔值时,但是 在你的情况下 blokace 什么都不返回(void )

此外

blokace 看起来像一个 eventMethod,所以这是您通常不调用但等待它被调用的东西,例如按下按钮、连接套接字、更改列表等

当您使用 if 语句时,结果应该是布尔值(真、假)。您的方法 return 无效。您基本上是在说 if (void) 不计算为 true 或 false。

也许您应该 return 从您的方法中判断真或假,然后它就会起作用。或者您可以 return 您的方法中的其他内容,然后检查值 returned。例如:

private string Blockace(object sender, EventArgs e)
{
    // do some work
    return "yes";
}

然后您可以检查 returned 值。但是您还需要发送 2 个参数:sender 和 e

if (Blockace(sender, e) == "yes")
{
   // do whatever you need
}

我可以从 blockace 方法签名看出它是一个事件处理程序。您需要从 UI 控件(单击或其他)重用其中的代码,但您还需要从您的代码中使用它。因此创建一个方法并将通用代码放在那里。然后您可以从事件处理程序和其他地方调用包含公共代码的方法。