Roslyn分析器代码修复 – 禁用预览选项

如何禁用C#项目中灯泡后显示的预览对话框?

我遇到的问题是,RegisterCodeFixesAsync调用数据库并递增id,这是两次完成(一次是在预览期间,第二次是在调用动作时),而不是仅增加一次,id增加两次

CodeAction具有单独的ComputePreviewOperationsAsync()ComputeOperationsAsync() 。 让他们回归不同的价值是我相信你正在寻找的。 但是,如果使用调用CodeAction.Create()的常用方法,则两者都将返回相同的值。

您可以做的是创建一个inheritance自CodeAction的自定义类,并按您希望的方式覆盖这些方法。 例如:

 class NoPreviewCodeAction : CodeAction { private readonly Func> createChangedSolution; public override string Title { get; } public override string EquivalenceKey { get; } public NoPreviewCodeAction( string title, Func> createChangedSolution, string equivalenceKey = null) { this.createChangedSolution = createChangedSolution; Title = title; EquivalenceKey = equivalenceKey; } protected override Task> ComputePreviewOperationsAsync( CancellationToken cancellationToken) { return Task.FromResult(Enumerable.Empty()); } protected override Task GetChangedSolutionAsync( CancellationToken cancellationToken) { return createChangedSolution(cancellationToken); } } 

此版本完全禁用预览。 另一种选择是使预览采用不同的路径,例如查询数据库以获取下一个值,但不更新它。