传递函数(带参数)作为参数?

klk*_*ens 23 c# parameters delegates

我想创建一个泛型,我可以将一个函数作为参数传递给我,但是这个函数可能包含参数本身......

int foo = GetCachedValue("LastFoo", methodToGetFoo)
Run Code Online (Sandbox Code Playgroud)

这样:

protected int methodToGetFoo(DateTime today)
{ return 2; // example only }
Run Code Online (Sandbox Code Playgroud)

本质上我想要一个方法来检查缓存的值,否则将根据传入的方法生成值.

思考?

Mar*_*ell 44

听起来你想要一个Func<T>:

T GetCachedValue<T>(string key, Func<T> method) {
     T value;
     if(!cache.TryGetValue(key, out value)) {
         value = method();
         cache[key] = value;
     }
     return value;
}
Run Code Online (Sandbox Code Playgroud)

然后呼叫者可以通过多种方式将其包裹起来; 对于简单的功能:

int i = GetCachedValue("Foo", GetNextValue);
...
int GetNextValue() {...}
Run Code Online (Sandbox Code Playgroud)

或涉及参数的地方,一个闭包:

var bar = ...
int i = GetCachedValue("Foo", () => GetNextValue(bar));
Run Code Online (Sandbox Code Playgroud)

  • 在这里真的很老,但关闭部分正是我正在寻找的 (3认同)

小智 11

使用System.Action和lambda表达式(anonimous方法).例如

    public void myMethod(int integer){

    //Do something

}

public void passFunction(System.Action methodWithParameters){

    //Invoke
    methodWithParameters();

}

//...

//Pass anonimous method using lambda expression
passFunction(() => myMethod(1234));
Run Code Online (Sandbox Code Playgroud)


mqp*_*mqp 5

您可以创建自己的委托,但在 C# 3.0 中,您可能会发现使用内置Func<T>委托系列来解决这个问题更方便。例子:

public int GetCachedValue(string p1, int p2,
                          Func<DateTime, int> getCachedValue)
{
    // do some stuff in here
    // you can call getCachedValue like any normal function from within here
}
Run Code Online (Sandbox Code Playgroud)

此方法将采用三个参数:一个字符串、一个 int 和一个接受 DateTime 并返回一个 int 的函数。例如:

int foo = GetCachedValue("blah", 5, methodToGetFoo);   // using your method
int bar = GetCachedValue("fuzz", 1, d => d.TotalDays); // using a lambda
Run Code Online (Sandbox Code Playgroud)

Func<T, U, V...>框架中存在不同的类型以适应具有不同数量参数的方法。