如何将 /features:strict(csc.exe)的等效项指定为 msbuild.exe 或在 .csproj 文件中?

How to specify the equivalent of /features:strict (of csc.exe) to msbuild.exe or in the .csproj file?

简介

考虑一下这个简单(而且不好)的 C# class:

using System;

namespace N
{
  static class C
  {
    static void M(DateTime d)
    {
      if (d == null)
        Console.WriteLine("Yes");
      else
        Console.WriteLine("No");
    }

    static void L(object o)
    {
      if (o is Nullable)
        Console.WriteLine("Yes");
      else
        Console.WriteLine("No");
    }

  }
}

两种方法 ML 都有严重的问题。

M 中,我们通过提升的 == 运算符询问不可空结构 DateTime 的值是否等于 null(自 DateTime 以来存在重载 operator ==)。这总是失败的,编译器可以在编译时判断,所以我们有一个无法到达的分支("Yes")。

N 中,我们询问 o 是否是 static class Nullable 的实例,但永远不会是这种情况(注意,静态 class Nullable与结构 Nullable<> 不同)。同样,这是开发人员的错误,"Yes" 语句无法访问。

在这些情况下我们确实需要编译时警告(或“错误警告”),对吗?

看起来,通过 C# 1.0 到 5.0 中使用的旧 C# 编译器中编译器错误 and/or 遗漏的逐渐积累,旧编译器未能出现预期的编译时警告。幸运的是,我们现在有 Roslyn/C# 6.0/Visual Studio 2015,预计会收到警告。但是不,因为 Roslyn 不想发出旧编译器不存在的警告(向后兼容?),这些情况仍然没有警告。

但是,如果您从命令行编译,使用csc.exe,您可以使用:

csc.exe /features:strict ... ...

你会得到你想要的警告! /features:strict 使 csc.exe 包含旧 C# 编译器“忘记”的警告。

我的问题

如何在 .csproj 文件中指定 /features:strictmsbuild.exe 命令行 的等效项?

有时,例如当我们的构建项目中有XAML时,直接使用csc.exe并不容易,我们必须使用.csproj文件并通过msbuild.exe.[=37=编译]

csproj 文件中直接支持此标志,只需添加:

<Features>strict</Features>

到您的 csproj 文件中的相应 PropertyGroup,构建后您将看到针对您的代码的此警告:

Warning CS8073 The result of the expression is always 'false' since a value of type 'DateTime' is never equal to 'null' of type 'DateTime?'

如果您想通过 msbuild 命令行界面执行相同操作,只需将此 属性 设置为 /p:Features=strict,如下所示:

/t:rebuild /p:Configuration=Debug /p:Platform=x64 /p:Features=strict