C# 如果可用,则从缓存获取,否则使用lambda设置值

C# 如果可用,则从缓存获取,否则使用lambda设置值,c#,ruby-on-rails,C#,Ruby On Rails,在Rails中,我可以这样写: value = Rails.cache.fetch("foo") { "bar" } 这样做的目的是尝试使用键“foo”获取缓存中的值,如果该值存在,则返回该值。否则,运行代码块,在本例中返回“bar”,并在缓存中设置该值 我想在C#中实现类似的东西,但我不确定如何实现。有可能吗?我假设可以使用lambda函数和匿名方法完成,例如: Cache.fetch(("foo") => "bar" ); var result = cache.Fetch("foo

在Rails中,我可以这样写:

value = Rails.cache.fetch("foo") { "bar" }
这样做的目的是尝试使用键“foo”获取缓存中的值,如果该值存在,则返回该值。否则,运行代码块,在本例中返回“bar”,并在缓存中设置该值

我想在C#中实现类似的东西,但我不确定如何实现。有可能吗?我假设可以使用lambda函数和匿名方法完成,例如:

Cache.fetch(("foo") => "bar" );
var result = cache.Fetch("foo", () => "bar");
public Cache<TKey, TValue>
{
    public TValue Fetch(TKey key, Func<TKey, TValue> defaultProvider)
    {
        ... fetch by key, and run defaultProvider otherwise...
    }
}
调用语法类似于:

Cache.fetch(("foo") => "bar" );
var result = cache.Fetch("foo", () => "bar");
public Cache<TKey, TValue>
{
    public TValue Fetch(TKey key, Func<TKey, TValue> defaultProvider)
    {
        ... fetch by key, and run defaultProvider otherwise...
    }
}
但显然,您需要一个合适的
缓存
类来开始。代码签名类似于:

Cache.fetch(("foo") => "bar" );
var result = cache.Fetch("foo", () => "bar");
public Cache<TKey, TValue>
{
    public TValue Fetch(TKey key, Func<TKey, TValue> defaultProvider)
    {
        ... fetch by key, and run defaultProvider otherwise...
    }
}
公共缓存
{
公共TValue获取(TKey、Func defaultProvider)
{
…按键获取,否则运行defaultProvider。。。
}
}
调用语法如下:

Cache.fetch(("foo") => "bar" );
var result = cache.Fetch("foo", () => "bar");
public Cache<TKey, TValue>
{
    public TValue Fetch(TKey key, Func<TKey, TValue> defaultProvider)
    {
        ... fetch by key, and run defaultProvider otherwise...
    }
}
但显然,您需要一个合适的
缓存
类来开始。代码签名类似于:

Cache.fetch(("foo") => "bar" );
var result = cache.Fetch("foo", () => "bar");
public Cache<TKey, TValue>
{
    public TValue Fetch(TKey key, Func<TKey, TValue> defaultProvider)
    {
        ... fetch by key, and run defaultProvider otherwise...
    }
}
公共缓存
{
公共TValue获取(TKey、Func defaultProvider)
{
…按键获取,否则运行defaultProvider。。。
}
}