无论提供的类型如何,都从C#generic返回null

Tyl*_*ler 0 c# generics

我正在为我们的Web服务编写内存缓存设置.这样我们就不必在每次需要设置时都访问数据库.我们有一种机制可以在更新数据库时使缓存无效.

缓存是一堆包含不同类型的字典,这里有两个字典:

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>>();
Run Code Online (Sandbox Code Playgroud)

我想编写一个从这些字典中获取值的泛型函数,如果在字典中找不到类别/设置,它应返回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;
}
Run Code Online (Sandbox Code Playgroud)

这将无法编译,因为:"无法将null转换为类型参数'TValue',因为它可能是一个不可为空的值类型.请考虑使用'default(TValue)'."

我想返回null而不是默认值(TValue)的原因是,在整数的情况下,调用者无法知道设置值是否实际为0或者是否在缓存中找不到它.

所以我的问题是,是否存在我可以放在一个泛型上的约束,它允许我返回null而不管提供的类型是什么?(我假设我需要使用Nullable但不确定如何.

Jon*_*eet 6

不 - 如果TValue是,int则它根本不能为空.

这正是为什么Dictionary.TryGetValue(这是你应该在内部使用,而不是使用ContainsKey然后第二次查找)返回bool并具有out值本身的参数.

这样说吧:假设TValuebyte.您的方法可以返回256个可能的值 - 但是有257种可能的结果:缓存中的256个可能的字节值,以及未找到它的可能性.