Roslyn 是否真的允许您为 CSharp 项目操纵 TreatWarningsAsErrors?

Does Roslyn actually allow you to manipulate TreatWarningsAsErrors for a CSharp project?

我正在尝试检索设置 TreatWarningsAsErrors,但我无法为我加载的解决方案的项目找到它。

我想要完成的是从项目文件中获取设置,并将其设置为 true(如果尚未设置)。接下来,我想让 Roslyn 使用新设置进行编译,这样我就可以检查这是否会破坏项目。

我看过很多地方,其中包括 Project.CompilationOptions。项目构建的大多数选项都在那里,除了这个。

CompilationOptions 包含所有构建设置,例如警告级别等。但是 TreatWarningsAsErrors 不存在。我是不是看错地方了?

我打开解决方案的方式类似于 FormatSolution sample:

var solutionFile = @"C:\ties\src\playground\EnforceTreatAllWarningsAsErrors\EnforceTreatAllWarningsAsErrors.sln";

var workspace = MSBuildWorkspace.Create();
var solution = workspace.OpenSolutionAsync(solutionFile).Result;
var project = solution.Projects.Single();

// warning level is there
var warningLevel = project.CompilationOptions.WarningLevel;

// treat warnings as errors is not there... The following doesn't compile :(
bool treatWarningsAsErrors = project.CompilationOptions.TreatWarningsAsErrors;

您正在寻找

compilationOptions.WithGeneralDiagnosticOption(ReportDiagnostic.Error)

Source