C#传递函数作为参数

Ole*_*rov 2 c#

不幸的是,我不能在类似的情况下看到这个问题

我必须执行许多类似的函数,我想创建一个函数来接受函数作为参数,例如

    int Search (Func<bool> func)
    {
        int start = Environment.TickCount;
        func();
        int end = Environment.TickCount;
        return end - start;
    }

    void SearchTime()
    { 
        int time1 = Search(list.Contains(item));
        int time2 = Search(dictionary.ContainsKey(anotheritem));
        /* some more code */
    }
Run Code Online (Sandbox Code Playgroud)

但实际上它说这个论点似乎并不合适.

UPD: 错误说:The most appropriate overloaded method has some invalid arguments

Guf*_*ffa 10

您尝试发送到方法的不是代理.

您可以使用lambda表达式为方法创建委托:

int time1 = Search(() => list.Contains(item));
int time2 = Search(() => dictionary.ContainsKey(anotheritem));
Run Code Online (Sandbox Code Playgroud)

的()代表零个输入参数.