简体   繁体   English

C#Func的目的是什么 <object> getObject?

[英]C# What is the purpose of Func<object> getObject?

I have found the following code snippet and was wondering what the purpose is of the Func<object> getObject property: 我找到了以下代码片段,并且想知道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 { }
}

How do you call this particular function by passing the Func property? 您如何通过传递Func属性来调用此特定函数?

You would call this with something like: 您可以这样称呼它:

InsertCacheItem("bob", () => "valuetocache", TimeSpan.FromHours(1));

But why do it this way? 但是为什么要这样呢? Why not just pass in "valuetocache"? 为什么不仅仅传递“ valuetocache”? Well, mainly due to the try..catch . 好吧,主要是由于try..catch The code as written means that even if the Func fails to execute then the calling code isn't impacted. 所编写的代码意味着,即使Func无法执行,调用代码也不会受到影响。

So: 所以:

InsertCacheItem("bob", () => MethodThatThrowsException(), TimeSpan.FromHours(1));

will still work, for example. 例如仍然可以使用。 It won't cache anything, but it won't bubble up exceptions to the calling code. 它不会缓存任何内容,但不会使调用代码的异常冒泡。

In the case of your code above, it's actually almost pointless other than to catch the exception. 对于上面的代码,除了捕获异常之外,实际上几乎没有任何意义。 You would more usually see this in a function to retrieve something from a cache. 您通常会在从缓存中检索内容的函数中看到此信息。 For example: 例如:

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;
}

Now we retrieve from the cache if we can, otherwise we call the potentially expensive operation to create the value again. 现在,如果可以的话,我们从缓存中进行检索,否则我们调用可能耗费成本的操作来再次创建该值。 For example: 例如:

var listOfZombies = GetCacheItem(
    "zombies", 
    () => GetZombiesFromDatabaseWhichWillTakeALongTime(), 
    TimeSpan.FromMinutes(10));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM