您只需将 /WarnAsError 添加到您的 dotnet 构建中即可。
示例代码:
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
int x = 0;
}
}
}
dotnet 构建的输出:
dotnet build
Microsoft (R) Build Engine version 16.10.0+4242f381a for .NET
Copyright (C) Microsoft Corporation. All rights reserved.
Determining projects to restore...
All projects are up-to-date for restore.
Program.cs(10,17): warning CS0219: The variable 'x' is assigned but its value is never used [ConsoleApp1.csproj]
ConsoleApp1 -> ConsoleApp1.dll
Build succeeded.
\Program.cs(10,17): warning CS0219: The variable 'x' is assigned but its value is never used [ConsoleApp1.csproj]
1 Warning(s)
0 Error(s)
Time Elapsed 00:00:00.79
dotnet build /WarnAsError 的输出:
dotnet build /WarnAsError
Microsoft (R) Build Engine version 16.10.0+4242f381a for .NET
Copyright (C) Microsoft Corporation. All rights reserved.
Determining projects to restore...
Restored ConsoleApp1.csproj (in 60 ms).
Program.cs(10,17): error CS0219: The variable 'x' is assigned but its value is never used [ConsoleApp1.csproj]
ConsoleApp1 -> ConsoleApp1.dll
Build FAILED.
Program.cs(10,17): error CS0219: The variable 'x' is assigned but its value is never used [ConsoleApp1.csproj]
0 Warning(s)
1 Error(s)
Time Elapsed 00:00:01.00
编辑:
OP 要求在警告时不要使构建失败。
您可以尝试将警告写入文件,然后计算该文件中的行数。
示例:
我把上面的代码加了几个变量:
int a = 0;
int b = 0;
int c = 0;
int d = 0;
int e = 0;
现在当我编译时,我收到 5 个警告。现在我将它添加到我的 dotnet 构建中:
$warningsFile = "SomeFile.log"
dotnet build -fl1 "/flp1:logFile=$warningsFile;warningsonly"
之后我可以简单地计算该文件中的行数。
使用 powershell:
gc $warningsFile | Measure-Object -Line
结果:
Lines Words Characters Property
----- ----- ---------- --------
5
我不确定这是否适用于所有情况,但至少它会告诉您是否有警告。
希望对你有帮助