使用委托来简化函数调用

Ada*_*m S 1 c#

我有一个布尔函数,用于许多其他函数的决策.并且每次都向用户提供消息框或允许其继续,具体取决于该函数的返回值.所以我的伪代码可能如下所示:

private bool IsConsented()
{
    //some business logic
}

private void NotReal()
{
    if (IsConsented())
    {
        //call function A
    }
    else
    {
        MessageBox.Show("Need consent first.");
    }
}

private void NotReal2()
{
    if (IsConsented())
    {
        //call function B
    }
    else
    {
        MessageBox.Show("Need consent first.");
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在寻找一种更简单的方法,而不是将if-else逻辑硬编码到我的每个函数中.我希望能够有这样的功能:

private void CheckConsent(function FunctionPointer)
        {
            if (IsConsented())
            {
                //call the function
                FunctionPointer();
            }
            else
            {
                MessageBox.Show("Need consent first.");
            }
        }
Run Code Online (Sandbox Code Playgroud)

这样我就可以将指针传递给函数.我真的怀疑这与委托有关,但我不知道语法,我不明白如何使用委托传递参数.

Ree*_*sey 5

您需要声明委托(或使用内置的委托,例如Action):

 private void CheckConsent(Action action)
 {
        if (IsConsented())
        {
             action();
        }
        else
        {
            MessageBox.Show("Need consent first.");
        }
 }
Run Code Online (Sandbox Code Playgroud)

然后你可以这样做:

 private void NotReal()
 {
      this.CheckConsent( () =>
      {
          // Do "NotReal" work here...
      });
 }
Run Code Online (Sandbox Code Playgroud)