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

Code is heuristically unreachable when getting object from cache

我有以下代码,这个想法很简单,如果对象在缓存中就获取它,如果不在缓存中则从数据源中检索它并将其保存到缓存中,我正在使用 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;
        }

这里发生了很多事情,但最重要的是,这是一个 ReSharper 错误 - 值当然可以为空,我有一个更小的例子来证明这一点。

首先,让我们弄清楚您的代码中发生了什么。我不得不深入研究您正在使用 returns a RedisValueStackExchange.Redis library that you're using. Your cache object is, in fact, an IDatabase, which is implemented by the RedisDatabase class. The StringGet 方法,这是一个结构。就其本身而言,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;
    }
}

reported把这个问题发给 JetBrains,他们会解决的。

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