日期:2014-05-16  浏览次数:20734 次

迭代器yield问题,有高手可以帮解决下吗?
本帖最后由 yi_piao 于 2014-02-14 20:00:40 编辑
下面是一个实现二叉树的类,其中继承IEnumenable<T>接口用GetEnumerator()实现foreach迭代功能,可是得到的结果却不对,为什么呢?


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BinaryTree
{
    public class Tree<TItem>:IEnumerable<TItem> where TItem : IComparable<TItem>
    {
        public Tree(TItem nodeValue)
        {
            this.NodeData = nodeValue;
            this.LeftTree = null;
            this.RightTree = null;
        }

        public void Insert(TItem newItem)
        {
            TItem currentNodeValue = this.NodeData;
            if (currentNodeValue.CompareTo(newItem) > 0)
            {
                if (this.LeftTree == null)
                {
                    this.LeftTree = new Tree<TItem>(newItem);
                }
                else
                {
                    this.LeftTree.Insert(newItem);
                }
            }
            else
            {
                if (this.RightTree == null)
                {
                    this.RightTree = new Tree<TItem>(newItem);
                }
                else
                {
                    this.RightTree.Insert(newItem);
                }
      &nb