代码分析避免过度复杂 - 只需设置命令

时间:2012-04-28 18:38:49

标签: c# code-analysis maintainability

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

2 个答案:

答案 0 :(得分:3)

答案 1 :(得分:1)

看起来可读,所以压制对我来说没问题(假设你不能改变RelayCommand)。

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

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

编辑:要通过删除每行上的代理创建来简化代码,您可以从

更改代码
new RelayCommand(_ => MoveRowDown(), _ => TaskIsSelected());

new RelayCommand(MoveRowDown, TaskIsSelected);

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

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

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

public RelayCommand(Action action, Func<bool> enabled)
 : this(_ => MoveRowDown(), _ => TaskIsSelected()) {}