【问题标题】:Why does Resharper Think This Code is Unreachable为什么 Resharper 认为此代码无法访问
【发布时间】:2020-08-27 08:27:30
【问题描述】:

在编码时,我注意到 ReSharper (v2019.1.1) 认为我的部分代码无法访问:

我已经学会信任 ReSharper,因此我构建了一个测试工具来查看发生了什么:

void Main()
{
    List<string> scopeList = new List<string>();
    Dictionary<string, string> customFields = new Dictionary<string, string>();

    var mainScope = new Scope();
    var subScope = new Scope();
    subScope.Parent = mainScope;

    dynamic currentState = new Tuple<String, int>("bob", 1565);
    mainScope.State = currentState;
    subScope.State = "Hello";

    WriteScopes(subScope, scopeList, customFields);

    Console.WriteLine(customFields);
    Console.WriteLine(scopeList);
}

public void WriteScopes(Scope scope, List<string> scopeList, Dictionary<string, string> customFields)
{
    var loopScope = scope;

    while (loopScope != null)
    {
        var loopState = loopScope.State;
        if (loopState == null) continue;
        if (loopState is (string name, var value))
        {
            customFields.Add(name, value.ToString());
        }
        else
        {
            scopeList.Add(loopState.ToString());
        }

        loopScope = loopScope.Parent;
    }
}

public class Scope
{
    public Scope Parent { get; set; }
    public object State { get; set; }
}

当我运行测试时,"Hello" 字符串似乎正在执行“无法访问的代码”。但正如我上面所说,我已经学会信任 ReSharper,所以我想知道发生了什么?

为什么 ReSharper 认为代码不可访问?

【问题讨论】:

  • 我正在Imgurmy VS 中编写WriteScopes 的代码,但似乎没有消息(我启用了Resharper 并启用了c# 8 功能,我的RS 版本是2019.3.4)
  • 启发式意味着可能,您的代码可能无法访问。当 resharper 确定您的代码不会被执行时,您会得到“检测到无法访问的代码”。它可能会更聪明地解决自己的问题。
  • @Marlonchosky - 根据您的评论,我已升级到最新版本 (v2020.1.2)。一旦我这样做了,代码部分就不再被列为不可访问。如果您想发表您的评论作为答案,我会接受。
  • @Vaccano 完成!!

标签: c# .net-core resharper


【解决方案1】:

好吧,我完全不知道为什么代码被标记为无法访问,但在 my VS 与 ReSharper 2019.3.4 中,我没有看到该消息。这可能是工具中的一个错误。

【讨论】:

  • 对于以后看到此内容的任何人,此问题已通过升级到 ReSharper 2020.1.2 为我解决。
猜你喜欢
  • 1970-01-01
  • 2012-04-11
  • 2018-08-22
  • 1970-01-01
  • 2011-02-21
  • 2018-09-23
  • 1970-01-01
  • 2014-04-29
  • 2020-06-12
相关资源
最近更新 更多