class IntIndexer
    {
        private string[] myDate;
        public string this[int pp]
        {
            get { return myDate[pp]; }
            set { myDate[pp]= value; }
        }
        public IntIndexer(int pInt)
        {
            myDate = new string[pInt];
        }
    }
    class test
    {
        static void Main()
        {
            IntIndexer myInd = new IntIndexer(5);
            myInd[1] = "中国人";
            myInd[4] = "日本人";
            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine(myInd[i]);
            }            foreach (int a in myInd)
            {
                Console.WriteLine(myInd);
            }
                Console.ReadKey();
        }
    }for语句可以正常输出,但foreach就不行了。
求解释!

解决方案 »

  1.   

    Console.WriteLine(myInd);
    改为
    Console.WriteLine(a);
      

  2.   

    应该是foreach(string a in  myInd)
    然后Console.WriteLine(a);
      

  3.   

    让这个类实现IEnumerable和IEnumerator接口,就能用foreach来遍历了。
      

  4.   

    看这里 -> http://msdn.microsoft.com/zh-cn/library/9yb8xew9.aspx
      

  5.   

    很明显,类型都不对,不出错才怪了! foreach(string str in myid).....
      

  6.   

    class IntIndexer应该实现IEnumerable接口才能使用foreach哈
        class IntIndexer:IEnumerable
        {
            private string[] myDate;
            public string this[int pp]
            {
                get { return myDate[pp]; }
                set { myDate[pp] = value; }
            }
            public IntIndexer(int pInt)
            {
                myDate = new string[pInt];
            }        public IEnumerator GetEnumerator()
            {
                for (int i = 0; i < myDate.Length; i++)
                {
                    yield return myDate[i];
                }
            }
        }
      

  7.   

    如果提示错误,再加上这一段就欧了
            #region IEnumerator Members        object IEnumerator.Current
            {
                get { throw new NotImplementedException(); }
            }        bool IEnumerator.MoveNext()
            {
                throw new NotImplementedException();
            }        void IEnumerator.Reset()
            {
                throw new NotImplementedException();
            }        #endregion