【问题标题】:DoesNotReturnAttribute doesn't mark a code after a call as unreachableDoesNotReturnAttribute 不会在调用后将代码标记为无法访问
【发布时间】:2020-05-24 07:08:46
【问题描述】:

我正在阅读文档并编写一些测试代码来检查新功能。对于DoesNotReturn属性it says

编译器将调用该方法后的任何代码标记为不可达,直到遇到适当的 catch 子句。

所以我写了下面的代码来测试一下:

using System;
using System.Diagnostics.CodeAnalysis;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Start");
        var resMsg = SomeMethod();
        Console.WriteLine($"resMsg: {resMsg}");
    }

    [DoesNotReturn]
    static string SomeMethod()
    {
        throw new Exception("Some test exception");
    }
}

我希望编译器在SomeMethod() 调用之后的下一行会出现类似“检测到无法访问的代码”的警告,但没有任何警告。为什么?

已编辑:

  • 项目使用C# 8.0

  • 可空上下文已启用

这是整个 *.csproj 文件的内容:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <LangVersion>8.0</LangVersion>
    <Nullable>enable</Nullable>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="SixLabors.ImageSharp" Version="1.0.0-rc0001"/>
    <PackageReference Include="SixLabors.ImageSharp.Drawing" Version="1.0.0-beta0007"/>
  </ItemGroup>
</Project>

【问题讨论】:

  • 我认为该属性仅与NRT分析有关,与一般代码可达性无关。
  • @JonSkeet 你能告诉NRT分析是什么意思吗?我试图用谷歌搜索这个术语,但没有发现任何与编程相关的内容
  • 可空引用类型分析。 (如,它只是关于 C# 8 可空引用类型的处理。)
  • @JonSkeet,老实说,我不知道这个属性与 Nullable Reference Type 分析有何关系。它是如何使用的,我该如何使用它?
  • 您链接到的整个页面都是关于可空引用类型分析的。标题是“保留属性有助于编译器的空状态静态分析”。如果你觉得你需要使用这些,你可能不需要。

标签: c# c#-8.0


【解决方案1】:

升级语言版本选择 C# 8.0,但不启用可空注释上下文或可空警告上下文。重新构建项目以确保它在没有警告的情况下构建。

reference

如第二段所述:

所有示例均假定 C# 8.0 或更高版本,并且代码位于可为空的上下文中。

所以您需要检查您的 .csproj 文件并确保启用了 Nullable 上下文。


<PropertyGroup>
  ...
  <Nullable>enable</Nullable>
  <LangVersion>8.0</LangVersion>
</PropertyGroup>

【讨论】:

  • 对不起,我忘了提到该项目已经指向 C# 8.0 并且启用了可为空的上下文。我刚刚编辑了我的帖子并添加了这些详细信息。
【解决方案2】:

在没有 DoesNotReturn 的情况下进行测试。编译器会给你一个警告吗?我测试过的,没有。见下文。

这个会产生警告

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Start");

        throw new Exception("Some test exception");

        var resMsg = SomeMethod();
        Console.WriteLine($"resMsg: {resMsg}");
    }

    static string SomeMethod()
    {
        throw new Exception("Some test exception");
    }
}

而这个没有

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Start");

        //throw new Exception("Some test exception");

        var resMsg = SomeMethod();
        Console.WriteLine($"resMsg: {resMsg}");
    }

    static string SomeMethod()
    {
        throw new Exception("Some test exception");
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-15
    • 2013-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多