我正在为我们的webservices编写内存缓存设置。这样我们就不需要每次需要设置时都需要访问数据库。我们有一种机制在数据库更新时使缓存失效。无论提供哪种类型,都从C#泛型返回null
缓存是一串包含不同类型的词典,这里的这些字典中的两种:
static readonly object StringValueCacheMutex = new object();
static readonly Dictionary<string, Dictionary<string, string>> StringValueCache = new Dictionary<string, Dictionary<string, string>>();
static readonly object IntegerValueCacheMutex = new object();
static readonly Dictionary<string, Dictionary<string, Int64>> IntegerValueCache = new Dictionary<string, Dictionary<string, Int64>>();
我想编写一个通用的函数,会从这些词典的值,如果类别/设置没有在字典中找到它应该返回null来表示它没有被发现。
问题是这些字典包含可为空和不可空的类型。
这里是通用的我想有:
public static TValue GetValueOrNull<TValue>(
IDictionary<string, Dictionary<string, TValue>> cacheDictionary,
object cacheMutex,
string categoryName,
string settingName)
{
TValue value = null;
lock (cacheMutex)
{
if (cacheDictionary.ContainsKey(categoryName))
{
if (cacheDictionary[categoryName].ContainsKey(settingName))
{
value = cacheDictionary[categoryName][settingName];
}
}
}
return value;
}
这不会编译因为:“无法将null转换为类型参数‘TValue’,因为它可能是一个非空的值类型考虑使用'而不是“默认(TValue)”。“
我想返回null而不是默认值(TValue)的原因是,在整数情况下,调用方无法知道设置值实际上是0还是它在缓存中找不到。
所以我的问题是,是否有限制,我可以把一个泛型,将允许我返回null,无论提供的类型? (我假设我需要使用可空,但不知道如何
与您的特定问题无关,但您可能会考虑使用'ReadWriterLock'(或者更好的是'ReaderWriterLockSlim'),因为多个读者可能没有理由互相阻止。 – dlev