如何编写一个动态搜索树视图的三角形的方法?

时间:2011-03-17 20:02:53

标签: c# properties

我正在创建一个(递归)方法,允许我指定根treenode,treenode属性和要匹配的值。

SearchAllTreeNodes(rootNode, Tag, "foo");

在此示例中,预期方法将返回其TreeNode属性与字符串“foo”匹配的Tag

我不确定如何处理方法的第二个参数:

public static TreeNode SearchAllTreeNodes(TreeNode rootNode, /* ?? */, string Value)
{
    /* ... */
}

如何指定要检查的对象的哪个属性?是否有推荐的方法来处理多个值类型,或者我应该为那些(int,bool)创建一些重载?

修改

感谢提供的答案,我能够完成以下方法:

public static TreeNode SearchAllTreeNodes(TreeNodeCollection nodeCollection, Func<TreeNode, bool> match)
{
    foreach (TreeNode tn in nodeCollection)
    {
        if (match(tn)) return tn;
        if (tn.Nodes.Count <= 0) continue;
        TreeNode f = SearchAllTreeNodes(tn.Nodes, match);
        if (f != null) return f;
    }
    return null;
}

像这样调用:

SearchAllTreeNodes(treeView.Nodes, node => node.Tag != null && (string)node.Tag == "foo")

或:

SearchAllTreeNodes(treeView.Nodes, node => node.Tag != null && (int)node.Tag == 42)

3 个答案:

答案 0 :(得分:3)

我会选择一个委托(在其中使用所需的值封装比较):

public static TreeNode SearchAllTreeNodes(TreeNode rootNode, Func<TreeNode, bool> match)
{
    if (match(rootNode))
    {
        /* ... */
    }
}

调用:

SearchAllTreeNodes(rootNode, node => node.Tag == "foo");

答案 1 :(得分:1)

我同意其他答案,你应该让一个委托来执行匹配,但是如果你真的想采用指定属性和值的方法,你可以使用反射并将属性名称指定为字符串:

public static TreeNode SearchAllTreeNodes(TreeNode rootNode, string property, string value)
{
  PropertyInfo propertyInfo = treeNode.GetType().GetProperty(property);
  if (propertyInfo.GetValue(treeNode, null).ToString() == value)
  {
    /* Do stuff */
  }
}

public static void Main(string[] args)
{
  /* ... */

  SearchAllTreeNodes(someNode, "Tag", "foo");
}

当然,请记住反射很慢,不建议在大量比较中运行上面的代码。你可以通过保持PropertyInfo对象并重用它来加速它,而不是每次都获得它。

答案 2 :(得分:0)

public static TreeNode SearchAllTreeNodes(TreeNode rootNode, Func<TreeNode, bool> matchCriteria, string Value)
{
  if (matchCriteria != null ) 
   {
      var result = matchCriteria(rootNode);
   }
}