using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace ConsoleApplication1
{
    class Program
    {
        public class student:IEnumerable<string>
        {
            private string no;
            private string name;
            private string sex;
            private string hobby;
            public IEnumerator<string> GetEnumerator()
            {
                yield return "no";
                yield return "name";
                yield return "sex";
                yield return "hobby";
            }
            public student()
            {
                no = "20010";
                name = "baomi";
                sex = "male";
                hobby = "computer game";
            }
            public string this[string item]
            {
                get
                {
                    switch(item)
                    {
                        case "no":
                            return no;
                        case "name":
                            return name;
                        case "sex":
                            return sex;
                        case "hobby":
                            return hobby;
                        default:
                            return "bad indexing";
                    }
                }                
            }
        }
        static void Main(string[] args)
        {
            student sd = new student();
            foreach (string item in sd)
            {
               Console.WriteLine(item + "=" + sd[item]);
            }
            Console.ReadKey();
        }
    }
}
错误    1    “ConsoleApplication1.Program.student”不实现接口成员“System.Collections.IEnumerable.GetEnumerator()”。“ConsoleApplication1.Program.student.GetEnumerator()”无法实现“System.Collections.IEnumerable.GetEnumerator()”,因为它没有匹配的返回类型“System.Collections.IEnumerator”。    D:\Documents\Visual Studio 2008\Projects\ConsoleApplication1\ConsoleApplication1\Program.cs    10    22    ConsoleApplication1怎么回事啊?

解决方案 »

  1.   

    你要实现签名为 IEnumerator GetEnumerator() 的方法。
      

  2.   

     public IEnumerator<string> GetEnumerator()
      {
      yield return "no";
      yield return "name";
      yield return "sex";
      yield return "hobby";
      }
    这个有什么问题?
      

  3.   

    嘿,没有说它有问题啊?!实现IEnumerable<string>接口的代码也需要实现IEnumerable接口,这就是使用.net接口的痛苦,它不像使用class继承那样自动化。而你没有实现IEnumerable接口。
    要说有什么问题,你的student可以循环返回一堆属性名字,我觉得很不实际。特别是手动去修改this里边的代码啊。不过这是设计问题,如果不考虑别人怎样理解 student 概念,而是为了理解 IEnumerable<T> 随便写的一个,那么也无可厚非。
      

  4.   

    在你的代码中,随便写上System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        throw new NotImplementedException();
    }这样也就编译通过了!