1

我正在尝试将对函数的引用作为参数传递

很难解释

我将编写一些示例伪代码

(calling function)

function(hello());

function(pass)
{
   if this = 0 then pass
   else
}

hello()
{
   do something here
}

对不起,如果它没有多大意义

但我正在尝试减少使用的代码,我认为这将是一个好主意。

我怎样才能在 C# 中做到这一点?

4

3 回答 3

7

您可以使用委托将代码传递给方法,例如Action 委托

void MyFunction(Action action)
{
    if (something == 0)
    {
        action();
    }
}

void Hello()
{
    // do something here
}

用法:

MyFunction(Hello);
于 2012-04-30T10:46:50.007 回答
6

我正在尝试将对函数的引用作为参数传递

很难解释

这可能很难解释,但很容易实现:下面的代码调用MyFunction将一段参数化的代码作为参数传递给它。

static void MyFunction(Action<string> doSomething) {
    doSomething("world");
}

static void Main(string[] args) {
    MyFunction((name) => {
        Console.WriteLine("Hello, {0}!", name);
    });
}

您可以使用系统(ActionFunc)提供的委托类型或编写您自己的委托类型。

于 2012-04-30T10:47:25.530 回答
0

这是一个例子:

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);
    }
}
于 2012-04-30T10:50:09.467 回答