2

我正在开发一些应用程序,它使用 TreeView 控件来表示业务对象。目前,业务对象和 TreeNode 之间的链接是通过 TreeNode 的 Tag 属性来维护的。我对此不太满意,因为我认为链接不够“紧密”。例如,可能有一个没有业务对象的 TreeNode 对象,我也想根据业务对象状态更新 TreeNode 图像。因此,我从 TreeNode 派生了我自己的特殊 TreeNode 类:

class ActionTreeNode : TreeNode
   {
      private Action mAction;

      public Action Action
      { get ... }

      public ActionTreeNode(Action action)
         : base()
      {
         if (action == null) throw new ArgumentNullException("action", "Paramter action must not be null.");

         mAction = action;
      }

    public void UpdateState()
      {
         switch (mAction.ActionState)
         {
            case ActionState.Passed:
               SelectedImageIndex = 3;
               ImageIndex = 3;
               break;
            case ActionState.Failed:
               SelectedImageIndex = 2;
               ImageIndex = 2;
               break;
            ...
         }

         return;
      }
   }

使用这种最小的方法,每次调用返回 TreeNode 对象的基类的属性或方法时,我都必须强制转换,如“(ActionTreeNode)myNode.Parent”。解决方案是覆盖/覆盖每个方法或属性并返回 ActionTreeNode 类型的对象。您认为,采用最小方法更合适,还是您会努力重新实现所有方法、属性以避免强制转换?谢谢。

4

2 回答 2

3

我喜欢最小的方法。如果您担心使用大量强制转换语句使代码混乱,只需创建一种方法在一个地方为您执行此操作:

private ActionTreeNode GetParent(ActionTreeNode node)
{
    return node.Parent as ActionTreeNode;
}

// in some method:
ActionTreeNode parent = GetParent(someNode);
if (parent != null)
{
    // the parent is an ActionTreeNode
}

不要忘记对返回值进行空检查,如果父级不是 ActionTreeNode...

于 2009-05-05T09:49:20.397 回答
2

我认为问题是你需要多长时间才能努力使它成为强类型。

权衡使一切“紧密”的成本与您和其他开发人员拥有可靠平台的成本。

在不了解更多信息的情况下,我个人认为我会强烈键入它,因为这也意味着对您的业务逻辑的任何更改(例如存储在树中的不同类型)都会导致编译失败,而不是可能的未知错误。

于 2009-05-05T09:58:26.303 回答