[英]What algorithm is used in this code?
此代碼檢查並取消選中Treeview控件的子節點。 此代碼中使用什么算法?
private int _callCountUp;
private int _callCountDn;
private void tvwPermissions_AfterCheck(object sender, System.Windows.Forms.TreeViewEventArgs e)
{
bool anyChecked = false;
if (_callCountDn == 0 && e.Node.Parent != null)
{
anyChecked = false;
foreach (TreeNode childNode in e.Node.Parent.Nodes)
{
if (childNode.Checked)
{
anyChecked = true;
break;
}
}
_callCountUp += 1;
if (anyChecked)
e.Node.Parent.Checked = true;
_callCountUp -= 1;
}
if (_callCountUp == 0)
{
foreach (TreeNode childNode in e.Node.Nodes)
{
_callCountDn += 1;
childNode.Checked = e.Node.Checked;
_callCountDn -= 1;
}
}
}
不確定是否有名稱。 這是很標准的,_callCountUp / Dn字段可避免在更改節點的Checked屬性導致AfterCheck事件處理程序再次運行時遇到麻煩。 當事件處理程序無限制地遞歸時,StackOverflow是非常典型的結果。
通用模式類似於:
private bool modifyingNodes;
private void treeview_AfterCheck(object sender, TreeViewEventArgs e) {
if (modifyingNodes) return;
modifyingNodes = true;
try {
// etc..
}
finally {
modifyingNodes = false;
}
}
finally塊可確保處理的異常(例如通過ThreadExceptionDialog)不會永久將狀態變量設置為true。 當然是可選的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.