数据结构模型如下:

public Class A
{
    public string Name{get;set;}
    public list<A> children{get;set;}
}

现要寻找一个子节点,目前代码如下:

        public A FindByName(string _name)
        {
            if (this.Name == _name)
                return this;
            else
            {
                for (int i = 0; i < this.children.Count; i++)                
                     return this.children[i].FindByName(_name);
            }
            return null;
        }

但是,VS编译器一直提示 i++是 "Unreachable code detected".

其运行结果也相差很多,这个循环只遍历了第0个孩子,孙子。。。

现正确的做法如下:

        public A FindByName(string _name)
        {
            if (this.Name == _name)
                return this;
            else
            {
                A p = null;
                for (int i = 0; i < this.children.Count; i++)
                {
                    p = this.children[i].FindByName(_name);
                    if (p != null)
                        break;
                }
                return p;
            }
        }