5

我有一个带有 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());
}
4

2 回答 2

4

由于使用了匿名方法,这是一个误报。该规则不会将编译器生成的分支识别为生成的代码。请参阅https://connect.microsoft.com/VisualStudio/feedback/details/555560/method-using-many-lambda-expressions-causes-high-cyclomatic-complexityhttps://connect.microsoft.com/VisualStudio/feedback /details/295703/incorrect-cyclomatic-complexity-with-lambdas用于现有错误报告。

于 2012-04-28T22:40:33.277 回答
1

看起来可读,所以抑制对我来说是可以的(假设你不能改变 RelayCommand)。

如果您可以控制 RelayCommand 类 - 添加构造函数RealayCommand(Action, Func<bool>)以消除额外的包装 lambda/委托创建。

如果您希望有更多按钮,请考虑切换到带有 { button, action, enabled } 条目的表格。

编辑:要通过删除每一行上的委托创建来简化代码,您可以更改代码

new RelayCommand(_ => MoveRowDown(), _ => TaskIsSelected());

new RelayCommand(MoveRowDown, TaskIsSelected);

通过添加设置文件本身的新构造函数:

public RelayCommand(Action action, Func<bool> enabled)
{
  this._execute = _ => action();
  this._enabled = _ => enabled();
}

或调用现有构造函数的新构造函数:

public RelayCommand(Action action, Func<bool> enabled)
 : this(_ => MoveRowDown(), _ => TaskIsSelected()) {}
于 2012-04-28T19:02:35.947 回答