Jac*_*k T 1 c# parameters function
我正在尝试将函数的引用作为参数传递
很难解释
我将写一些示例伪代码
(calling function)
function(hello());
function(pass)
{
if this = 0 then pass
else
}
hello()
{
do something here
}
Run Code Online (Sandbox Code Playgroud)
对不起,如果它没有多大意义
但我正在尝试减少使用过的代码,我认为这是一个好主意.
我怎么能在C#中做到这一点?
void MyFunction(Action action)
{
if (something == 0)
{
action();
}
}
void Hello()
{
// do something here
}
Run Code Online (Sandbox Code Playgroud)
用法:
MyFunction(Hello);
Run Code Online (Sandbox Code Playgroud)
我正在尝试将一个函数的引用作为参数传递
很难解释
可能很难解释,但它很容易实现:下面的代码调用MyFunction将一段参数化的代码作为参数传递给它。
static void MyFunction(Action<string> doSomething) {
doSomething("world");
}
static void Main(string[] args) {
MyFunction((name) => {
Console.WriteLine("Hello, {0}!", name);
});
}
Run Code Online (Sandbox Code Playgroud)
您可以使用系统提供的委托类型(Action和Func)或编写自己的.