C# Func<object> getObject 的目的是什么?
C# What is the purpose of Func<object> getObject?
我找到了以下代码片段,想知道 Func<object> getObject
属性:
的目的是什么
public void InsertCacheItem(string key, Func<object> getObject, TimeSpan duration)
{
try
{
var value = getObject();
if (value == null)
return;
key = GetCacheKey(key);
_cache.Insert(
key,
value,
null,
System.Web.Caching.Cache.NoAbsoluteExpiration,
duration,
System.Web.Caching.CacheItemPriority.Normal,
null);
}
catch { }
}
如何通过传递 Func 属性 来调用这个特定的函数?
你可以这样称呼它:
InsertCacheItem("bob", () => "valuetocache", TimeSpan.FromHours(1));
但为什么要这样做呢?为什么不直接传入 "valuetocache"?嗯,主要是由于try..catch
。编写的代码意味着即使 Func
无法执行,调用代码也不会受到影响。
所以:
InsertCacheItem("bob", () => MethodThatThrowsException(), TimeSpan.FromHours(1));
例如,仍然有效。 它不会缓存任何内容,但不会冒泡调用代码的异常。
对于您上面的代码,除了捕获异常之外,它实际上几乎毫无意义。您通常会在从缓存中检索内容的函数中看到它。例如:
public object GetCacheItem(string key, Func<object> getObject, TimeSpan duration)
{
var value = GetItemFromCache(key);
if (value == null)
{
value = getObject();
_cache.Insert(
key,
value,
null,
System.Web.Caching.Cache.NoAbsoluteExpiration,
duration,
System.Web.Caching.CacheItemPriority.Normal,
null);
}
return value;
}
如果可以的话,现在我们从缓存中检索,否则我们调用潜在的昂贵操作来再次创建值。例如:
var listOfZombies = GetCacheItem(
"zombies",
() => GetZombiesFromDatabaseWhichWillTakeALongTime(),
TimeSpan.FromMinutes(10));
我找到了以下代码片段,想知道 Func<object> getObject
属性:
public void InsertCacheItem(string key, Func<object> getObject, TimeSpan duration)
{
try
{
var value = getObject();
if (value == null)
return;
key = GetCacheKey(key);
_cache.Insert(
key,
value,
null,
System.Web.Caching.Cache.NoAbsoluteExpiration,
duration,
System.Web.Caching.CacheItemPriority.Normal,
null);
}
catch { }
}
如何通过传递 Func 属性 来调用这个特定的函数?
你可以这样称呼它:
InsertCacheItem("bob", () => "valuetocache", TimeSpan.FromHours(1));
但为什么要这样做呢?为什么不直接传入 "valuetocache"?嗯,主要是由于try..catch
。编写的代码意味着即使 Func
无法执行,调用代码也不会受到影响。
所以:
InsertCacheItem("bob", () => MethodThatThrowsException(), TimeSpan.FromHours(1));
例如,仍然有效。 它不会缓存任何内容,但不会冒泡调用代码的异常。
对于您上面的代码,除了捕获异常之外,它实际上几乎毫无意义。您通常会在从缓存中检索内容的函数中看到它。例如:
public object GetCacheItem(string key, Func<object> getObject, TimeSpan duration)
{
var value = GetItemFromCache(key);
if (value == null)
{
value = getObject();
_cache.Insert(
key,
value,
null,
System.Web.Caching.Cache.NoAbsoluteExpiration,
duration,
System.Web.Caching.CacheItemPriority.Normal,
null);
}
return value;
}
如果可以的话,现在我们从缓存中检索,否则我们调用潜在的昂贵操作来再次创建值。例如:
var listOfZombies = GetCacheItem(
"zombies",
() => GetZombiesFromDatabaseWhichWillTakeALongTime(),
TimeSpan.FromMinutes(10));