gpt4 book ai didi

c# - Func,T> 的示例和用法

转载 作者:太空宇宙 更新时间:2023-11-03 22:41:03 25 4
gpt4 key购买 nike

我一直在尝试想出一个使用 Func<Func<T>,T> 的案例会有用的。

想出 Func<T,T> 的例子是微不足道的,例如

Func<int,int> square = n => n*n;

但我无法想出使用类似 Func<Func<T>,T> 的示例案例

另一方面,Func<T,Func<T>> 的用法

似乎微不足道,例如

Func<int,Func<int,int>> k = k => square;

Func<Func<T>,T> 是否有任何众所周知的用例?或 Func<T,Func<T>>或一些讨论类似主题的引用资料?

最佳答案

幸好你没有要求一个简单的用例:)

用例:假设您需要汇集来自设备的值。访问设备很费力(在某些指标上)。有时您可以接受旧值(无法真正访问设备),有时您需要绝对最新值(必须访问设备),有时您需要介于两者之间。哦,您还必须能够即时更改合并值和/或设备。

下面是满足上述要求的解决方案:

public class Cache
{
public int? CachedValue { get; private set;}
public DateTime cacheLastRetrieved { get; private set; }

public void SetCache(int value)
{
CachedValue = value;
cacheLastRetrieved = DateTime.Now;
}

public Func<Func<int>, int> CacheStrategy;
public void ResetCache()
{
CachedValue = null;
}

public int Get(Func<int> f)
{
return CacheStrategy(f);
}
}
public static class CacheFactory
{
private static Func<Func<int>, int>
MakeCacheStrategy(Cache cache, Func<Cache, bool> mustGetRealValue)
{
return f =>
{
if (mustGetRealValue(cache))
{
int value = f();
cache.SetCache(value);
return value;
}
return (int)cache.CachedValue;
};
}

public static Func<Func<int>, int> NoCacheStrategy(Cache cache)
{
return MakeCacheStrategy(cache, c => true);
}

public static Func<Func<int>, int> ForeverCacheStrategy(Cache cache)
{
return MakeCacheStrategy(cache, c => c.CachedValue == null);
}

public static Func<Func<int>, int>
SimpleCacheStrategy(Cache cache, TimeSpan keepAliveTime)
{
return MakeCacheStrategy(cache,
c => c.CachedValue == null
|| c.cacheLastRetrieved + keepAliveTime < DateTime.Now);
}
}
public class Device
{
static Random rnd = new Random();
public int Get()
{
return rnd.Next(0, 100);
}
}
public class Program
{
public static void Main()
{
Device dev = new Device();
Cache cache = new Cache();

cache.ResetCache();
cache.CacheStrategy = CacheFactory.NoCacheStrategy(cache);
Console.Write("no cache strategy: ");
for (int i = 0; i < 10; ++i)
{
Console.Write(cache.Get(dev.Get) + " ");
}
Console.WriteLine();

cache.ResetCache();
cache.CacheStrategy = CacheFactory.ForeverCacheStrategy(cache);
Console.Write("forever cache strategy: ");
for (int i = 0; i < 10; ++i)
{
Console.Write(cache.Get(dev.Get) + " ");
}
Console.WriteLine();

cache.ResetCache();
cache.CacheStrategy
= CacheFactory.SimpleCacheStrategy(cache, TimeSpan.FromMilliseconds(300));
Console.Write("refresh after 300ms strategy: ");
for (int i = 0; i < 10; ++i)
{
Console.Write(cache.Get(dev.Get) + " ");
System.Threading.Thread.Sleep(TimeSpan.FromMilliseconds(100));
}
Console.WriteLine();
}
}

示例输出:

no cache strategy:            70 29 9 16 61 32 10 77 14 77 
forever cache strategy: 96 96 96 96 96 96 96 96 96 96
refresh after 300ms strategy: 19 19 19 22 22 22 91 91 91 10

关于c# - Func<Func<T>,T> 的示例和用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52156527/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com