c# – 代码分析避免过度复杂 – 只需设置命令
作者:互联网
我有一个带有16个按钮的WPF表单.当我的视图模型初始化时,我需要将所有16个设置为RelayCommand对象.这是我的所有Initialize()方法,但这会导致代码分析错误CA1502:AvoidExcessiveComplexity.
这是抑制CA警告的好例子,还是有更优雅的方法来设置这些命令而不会导致CA违规?
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "Simply setting the commands")]
private void Initialize()
{
this.AddApplicationCommand = new RelayCommand(_ => AddApplication());
this.DeleteApplicationCommand = new RelayCommand(_ => DeleteApplication(), _ => ApplicationIsSelected);
this.RefreshApplicationsCommand = new RelayCommand(_ => RefreshApplications());
this.SaveApplicationCommand = new RelayCommand(_ => SaveApplication(), _ => ApplicationIsSelected);
this.ForceInstallationCommand = new RelayCommand(_ => ForceInstallation(), _ => ApplicationIsSelected);
this.DeleteForceInstallationCommand = new RelayCommand(_ => DeleteForceInstallation(), _ => ApplicationIsSelectedAndForceExists());
this.AddTaskCommand = new RelayCommand(_ => AddTask(), _ => ApplicationIsSelected);
this.EditTaskCommand = new RelayCommand(_ => EditTask(), _ => TaskIsSelected());
this.DeleteTaskCommand = new RelayCommand(_ => DeleteTask(), _ => TaskIsSelected());
this.ImportTasksCommand = new RelayCommand(_ => ImportTasks(), _ => ApplicationIsSelected);
this.ExportTasksCommand = new RelayCommand(_ => ExportTasks(), _ => TaskIsSelected());
this.ImportLegacyTasksCommand = new RelayCommand(_ => ImportLegacyTasks(), _ => ApplicationIsSelected);
this.MoveTaskUpCommand = new RelayCommand(_ => MoveRowUp(), _ => TaskIsSelected());
this.MoveTaskDownCommand = new RelayCommand(_ => MoveRowDown(), _ => TaskIsSelected());
this.AddVariableGroupCommand = new RelayCommand(_ => AddVariableGroup());
this.RemoveVariableGroupCommand = new RelayCommand(_ => RemoveVariableGroup(), _ => VariableGroupIsSelected());
}
解决方法:
由于使用匿名方法,这是误报.该规则不会将编译器生成的分支识别为生成的代码.有关现有错误报告,请参阅https://connect.microsoft.com/VisualStudio/feedback/details/555560/method-using-many-lambda-expressions-causes-high-cyclomatic-complexity和https://connect.microsoft.com/VisualStudio/feedback/details/295703/incorrect-cyclomatic-complexity-with-lambdas.
标签:c,code-analysis,maintainability 来源: https://codeday.me/bug/20190626/1290741.html