从缓存中获取对象时,代码是启发式无法访问的

时间:2015-08-04 16:28:24

标签: c# resharper fxcop

我有以下代码,想法很简单,如果对象在缓存中获取它,如果没有然后从数据源检索它并将其保存到缓存中,我使用resharper并且我得到了这个警告但是无法理解为什么

 public static ModulosPorUsuario GetModulesForUser(string identityname)
        {
            // It needs to be cached for every user because every user can have different modules enabled.
            var cachekeyname = "ApplicationModulesPerUser|" + identityname;

            var cache = CacheConnectionHelper.Connection.GetDatabase();
            ModulosPorUsuario modulosUsuario;

            //get object from cache
            string modulosUsuariosString = cache.StringGet(cachekeyname);

            // ReSharper disable once ConditionIsAlwaysTrueOrFalse
            if (modulosUsuariosString != null)
            {
                //conver string to our object
                modulosUsuario = JsonConvert.DeserializeObject<ModulosPorUsuario>(modulosUsuariosString);
                return modulosUsuario;
            }
            // ReSharper disable once HeuristicUnreachableCode
            modulosUsuario = DbApp.ModulosPorUsuario.Where(p => p.Email == identityname).FirstOrDefault();

            //convert object to json string
            modulosUsuariosString = JsonConvert.SerializeObject(modulosUsuario);

            //save string in cache
            cache.StringSet(cachekeyname, modulosUsuariosString, TimeSpan.FromMinutes(SettingsHelper.CacheModuleNames));
            return modulosUsuario;
        }

1 个答案:

答案 0 :(得分:5)

这里发生了很多事情,但最重要的是,这是一个ReSharper错误 - 值肯定是空的,我有一个更小的例子来证明它。

首先,让我们弄清楚代码中发生了什么。我不得不深入挖掘你正在使用的StackExchange.Redis库。事实上,cache对象是IDatabase,由RedisDatabase类实现。您正在使用的StringGet方法会返回RedisValue,这是一个结构。这本身就足以说明为什么ReSharper告诉你它永远不会是空的 - 价值类型不能!

但是,您要将结果放入string变量中!这是有效的,因为RedisValue结构定义了一堆implicit operators来将值转换为请求的类型。如果是字符串,请注意如果blob为空,则返回空字符串:

RedisValue.cs

/// <summary>
/// Converts the value to a String
/// </summary>
public static implicit operator string(RedisValue value)
{
    var valueBlob = value.valueBlob;
    if (valueBlob == IntegerSentinel)
        return Format.ToString(value.valueInt64);
    if (valueBlob == null) return null;

    if (valueBlob.Length == 0) return "";
    try
    {
        return Encoding.UTF8.GetString(valueBlob);
    }
    catch
    {
        return BitConverter.ToString(valueBlob);
    }
}

但是从这段代码可以看出,字符串也可以是null

这使得ReSharper标记该行不正确,并且可以使用较小的示例进行复制:

static void Main(string[] args)
{
    string value = MyStruct.GetValue();
    if (value == null) // <- ReSharper complains here, but the value is null!
    {
        return;
    }
}

public struct MyStruct
{
    public static MyStruct GetValue() => new MyStruct();

    public static implicit operator string(MyStruct s)
    {
        return null;
    }
}

I reported这个问题给JetBrains,他们会修复它。

与此同时,您可能希望保留该评论,禁用ReSharper警告。