c# - TreeNode.Nodes.ContainsKey 的算法是什么

标签 c# treenode

我对 TreeNode.Nodes.ContainsKey(string key) 感到困惑,它是否在其子项中递归搜索键,或者仅使用常规 for 循环在其子项中搜索。
如果它递归地搜索键,是否有一种方法只在其子项中搜索?

最佳答案

根据Reference Source , ContainsKey 执行以下操作:

    public virtual bool ContainsKey(string key) {
       return IsValidIndex(IndexOfKey(key)); 
    }

该方法的作用是:

    public virtual int  IndexOfKey(String key) {
        // Step 0 - Arg validation
        if (string.IsNullOrEmpty(key)){
            return -1; // we dont support empty or null keys.
        }

        // step 1 - check the last cached item
        if (IsValidIndex(lastAccessedIndex))
        {
            if (WindowsFormsUtils.SafeCompareStrings(this[lastAccessedIndex].Name, key, /* ignoreCase = */ true)) {
                return lastAccessedIndex;
            }
        }

        // step 2 - search for the item
        for (int i = 0; i < this.Count; i ++) {
            if (WindowsFormsUtils.SafeCompareStrings(this[i].Name, key, /* ignoreCase = */ true)) {
                lastAccessedIndex = i;
                return i;
            }
        }

        // step 3 - we didn't find it.  Invalidate the last accessed index and return -1.
        lastAccessedIndex = -1;
        return -1;
    }

    private bool IsValidIndex(int index) {
        return ((index >= 0) && (index < this.Count));
    }

看来它只是尝试查找 key 的索引,如果它有效,则意味着该 key 必须存在。

关于c# - TreeNode.Nodes.ContainsKey 的算法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44742832/

相关文章:

c# excel 如何在已用范围内查找第一个单元格。

c - 如何用C语言制作可遍历的树数据结构

c# - 创建自定义 TreeView/TreeNode

java - 检查输入到树中的有效路径(字符串)时遇到问题

c# - 在 TreeView c# 中向上移动树节点的处理程序崩溃

c# - 处理应用程序重新设计

c# - Odbc 命令。表名参数化

c# - 从 Button 链接下载文件到 C 盘上的特定文件夹

c# - 在 dbml 文件中为 LINQ to SQL 生成关联的问题

c - 从根指针指向的二叉搜索树中删除数据