且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

“将所有警告视为错误,除了..."在 Visual Studio 中

更新时间:2022-10-19 10:48:14

在 Visual Studio 2022 中,我们有一个新的项目属性 UI,其中包括一个编辑器.

构建下 |错误和警告 如果您将 Treat warnings as errors 设置为 All,则会出现另一个属性,允许您免除特定警告被视为错误:p>

这会将以下属性添加到您的项目中:

<WarningsNotAsErrors>618,1030,1701,1702</WarningsNotAsErrors>

In Visual Studio, I can select the "Treat warnings as errors" option to prevent my code from compiling if there are any warnings. Our team uses this option, but there are two warnings we would like to keep as warnings.

There is an option to suppress warnings, but we DO want them to show up as warnings, so that won't work.

It appears that the only way to get the behavior we want is to enter a list of every C# warning number into the "Specific warnings" text box, except for the two we want treated as warnings.

Besides the maintenance headache, the biggest disadvantage to this approach is that a few warnings do not have numbers, so they can't be referenced explicitly. For example, "Could not resolve this reference. Could not locate assembly 'Data....'"

Does anyone know of a better way to do this?


Clarifying for those who don't see immediately why this is useful. Think about how most warnings work. They tell you something is a little off in the code you just wrote. It takes about 10 seconds to fix them, and that keeps the code base cleaner.

The "Obsolete" warning is very different from this. Sometimes fixing it means just consuming a new method signature. But if an entire class is obsolete, and you have usage of it scattered through hundreds of thousands of lines of code, it could take weeks or more to fix. You don't want the build to be broken for that long, but you definitely DO want to see a warning about it. This isn't just a hypothetical case--this has happened to us.

Literal "#warning" warnings are also unique. I often want to check it in, but I don't want to break the build.

In Visual Studio 2022 we have a new Project Properties UI which includes an editor for this.

Under Build | Errors and Warnings if you set Treat warnings as errors to All, then another property appears which allows you to exempt specific warnings from being treated as errors:

This will add the following property to your project:

<WarningsNotAsErrors>618,1030,1701,1702</WarningsNotAsErrors>