2014-02-27 111 views
2

如何定义一个函数,该函数需要另一个在c#中返回bool的函数?带有可变参数的函数作为另一个函数的参数

为了澄清,这是我想什么用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")); 
} 

在我的例子上述组合Execute功能与bind得到预期的结果。

背景:

我有一大堆的功能,每次返回一个INT但由相同的错误校验码包围不同的参数个数。一个庞大的代码重复,我想避免...

回答

1

你可以用Func来实现你想要的。例如

void Execute(Func<bool> myFunc) 
{ 
    if(myFunc() == false) 
    { 
     // Show error 
    } 
} 

然后,您可以定义Func键既可以作为一种方法,或λ:

// Define a method 
private bool MethodFunc() {} 

// Pass in the method 
Execute(MethodFunc) 

// Pass in the Lambda 
Execute(() => { return true; }); 

你不nececssairly需要传递的,你现在可以从访问它们的参数来电者的范围:

Execute(() => { return myBool; }); 
Execute(() => { return String.IsNullOrEmpty(myStr); }); 
+0

A'Func '是一个不带参数返回bool的函数,即与C++'Func '相同的函数吗? –

+0

但是你现在可以通过调用lambda来访问它们 - 所以你不需要明确地在方法签名中定义它们。 – Ian

0
without argument do this 

    void Execute(Func<bool> fctn) 
    { 
     if(fctn()) 
     { 
      show_error(); 
     } 
    } 

    with arguments you can do something like this: 

    void Execute<T>(Func<T[],bool> fctn) 
    { 
     var v = new T[4]; 
     if(fctn(v)) 
     { 
      show_error(); 
     } 
    } 
+0

如何在具有参数的函数(绑定部分)中使用它? –

1

我的解决方案,可以执行任何功能,任何输入参数,与任何回报,这是一个非常通用的实现

例子:

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)); 
+0

为什么使用'Invoke'来调用函数,而不是直接调用它? –

+0

它更容易,如果你需要传递参数 –

相关问题