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