我对 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/