簡體   English   中英

將函數(帶參數)作為參數傳遞?

[英]Passing a Function (with parameters) as a parameter?

我想創建一個泛型,我可以將一個函數作為參數傳遞給它,但是這個函數可能包含參數本身,所以......

int foo = GetCachedValue("LastFoo", methodToGetFoo)

這樣:

protected int methodToGetFoo(DateTime today)
{ return 2; // example only }

本質上,我想要一個方法來檢查緩存中的值,否則將根據傳入的方法生成值。

想法?

聽起來你想要一個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;
}

然后調用者可以通過多種方式包裝它; 對於簡單的功能:

int i = GetCachedValue("Foo", GetNextValue);
...
int GetNextValue() {...}

或者在涉及參數的地方,一個閉包:

var bar = ...
int i = GetCachedValue("Foo", () => GetNextValue(bar));

使用System.Action和 lambda 表達式(匿名方法)。 例如:

public void myMethod(int integer) {     
    // Do something
}

public void passFunction(System.Action methodWithParameters) {
    // Invoke
    methodWithParameters();
}

// ...

// Pass anonymous method using lambda expression
passFunction(() => myMethod(1234));

您可以創建自己的委托,但在 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
}

此方法將采用三個參數:一個字符串、一個 int 和一個接受 DateTime 並返回一個 int 的函數。 例如:

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

框架中存在不同的Func<T, U, V...>等類型,以適應具有不同數量參數的方法。

methodToGetFoo方法創建一個委托

public delegate object GenerateValue(params p);
public event GenerateValue OnGenerateValue;

定義 GetCachedValue 以使用委托

int GetCachedValue(string key, GenerateValue functionToCall);

然后在 OnGenerateValue 的實現中,您可以檢查參數。

是我開始的一些簡單的事情,可以更進一步(就像我為商業項目所做的那樣)。

在我的情況下,這是緩存 Web 服務調用,並使用了類似的東西:

WebService ws = new WebService();
var result = ws.Call( x => x.Foo("bar", 1));  // x is the ws instance

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM