您询问了一个示例,说明为什么要将函数作为参数传递,我有一个完美的示例,并认为它可以帮助您理解,它非常学术,但显示了用途。假设您有一个 ListResults() 方法和 getFromCache() 方法。而是进行大量检查缓存是否为空等。您可以将任何方法传递给 getCache ,然后仅在 getFromCache 方法中的缓存为空时调用它:
_cacher.GetFromCache(delegate { return ListResults(); }, "ListResults");
public IEnumerable
{
var cache = _cacheProvider.GetCachedItem(key);
//you could even have a UseCache bool here for central control
if (cache == null)
{
//you could put timings, logging etc. here instead of all over your code
cache = item.Invoke();
_cacheProvider.AddCachedItem(cache, key, minutesToCache);
}
return cache;
}