C# 将变量参数作为另一个函数的参数的函数

C# 将变量参数作为另一个函数的参数的函数,c#,C#,如何定义一个函数,该函数需要另一个函数返回c#中的布尔值 澄清一下,这就是我想用C++做的: void Execute(boost::function<int(void)> fctn) { if(fctn() != 0) { show_error(); } } int doSomething(int); int doSomethingElse(int, string); int main(int argc, char *argv[]) {

如何定义一个函数,该函数需要另一个函数返回c#中的布尔值

澄清一下,这就是我想用C++做的:

void Execute(boost::function<int(void)> fctn)
{
    if(fctn() != 0)
    {
        show_error();
    }
}

int doSomething(int);
int doSomethingElse(int, string);

int main(int argc, char *argv[])
{
    Execute(boost::bind(&doSomething, 12));
    Execute(boost::bind(&doSomethingElse, 12, "Hello"));
}
void执行(boost::function fctn)
{
如果(fctn()!=0)
{
显示_错误();
}
}
int剂量测定法(int);
int doSomethingElse(int,string);
int main(int argc,char*argv[])
{
执行(boost::bind(&doSomething,12));
执行(boost::bind(&doSomethingElse,12,“Hello”);
}
在我上面的示例中,
Execute
函数与
bind
结合使用,可以获得预期的结果

背景:


我有一组函数,每个函数都返回一个int,但参数计数不同,它们被相同的错误检查代码包围。我希望避免大量的代码重复…

您可以通过使用。比如说

void Execute(Func<bool> myFunc)
{
   if(myFunc() == false)
   {
      // Show error
   }
}
您无需传入参数,因为现在可以从调用者的作用域访问它们:

Execute(() => { return myBool; });
Execute(() => { return String.IsNullOrEmpty(myStr); });
无参数执行此操作
无效执行(函数fctn)
{
if(fctn())
{
显示_错误();
}
}  
使用参数,您可以执行以下操作:
无效执行(函数fctn)
{
var v=新的T[4];
如果(fctn(v))
{
显示_错误();
}
}

使用我的解决方案,您可以执行任何函数、任何输入参数和任何返回,这是一个非常通用的实现

示例:

public T YourMethod<T>(Func<T> functionParam)
{
   return functionParam.Invoke();
}

public bool YourFunction(string foo, string bar, int intTest)
{
    return true;
}
YourMethod<bool>(() => YourFunction("bar", "foo", 1));
YourMethod(() => YourFunction("bar", "foo", 1));

如何将其用于具有参数的函数(绑定部分)?a
Func
是一个返回bool而不带参数的函数,即,与C++<代码> FUNC相同,但现在可以通过调用lambda访问它们——所以您不需要在方法签名上定义它们。为什么使用“代码>调用Kuk/C++”来调用函数,而不是直接调用它?如果需要传递参数,那么它更容易。
YourMethod<bool>(() => YourFunction("bar", "foo", 1));
YourMethod(() => YourFunction("bar", "foo", 1));