我按照书上的内容作了,可是,那个,用字符串做的索引不能识别:下面贴出部分代码,希望各位大虾指点下,谢谢啦, 嘿嘿
   
//索引器所在的类。
 class MyClass
    {
        private string name;        public string Name
        {
            get { return name; }
            set { name = value; }
        }
        private Student[] students=new Student[3];        internal Student[] Students
        {
            get { return students; }
            set { students = value; }
        }
        public MyClass()
        {
            
            
            students[0] = new Student("Mcgrady", "basketball");
            students[1] = new Student("Bryant", "cooking");
        }
        public Student this[int index]
        {
            get { return students[index]; }
        }
        public Student this[string name]
        {
            get
            {
                int i;
                bool found = false;
                for (i = 0; i < students.Length; i++)
                {
                    if (students[i].Name == name)
                    {
                        found = true;
                        break;
                    }
                }                if (found)
                {
                    return students[i];
                }
                else
                {
                    return null;
                }
            }
        }    }
//索引元素的类。
  class Student
    {
        private string name;        public string Name
        {
            get { return name; }
            set { name = value; }
        }
        private string hobby;        public string Hobby
        {
            get { return hobby; }
            set { hobby = value; }
        }
        public Student(string name, string hobby)
        {
            this.name = name;
            this.hobby = hobby;
        }
    }
//测试类。
class Program
    {
        static void Main(string[] args)
        {
            MyClass mc = new MyClass();
            Console.WriteLine(mc.Students[0].Name);
            Console.WriteLine(mc.Students["Bryant"].Hobby);
        }
    }
//报错语句
错误 1 无法将类型“string”隐式转换为“int” D:\Shot\IndexTest\IndexTest\Program.cs 13 43 IndexTest
谢谢大家了, 困扰我很久了呀, 

解决方案 »

  1.   

            static void Main(string[] args) 
            { 
                MyClass mc = new MyClass(); 
                Console.WriteLine(mc.Students[0].Name); 
                Console.WriteLine(mc.Students["Bryant"].Hobby); 
            } 你还不明白索引器的用法。以上代码应该改为:        static void Main(string[] args) 
            { 
                MyClass mc = new MyClass(); 
                Console.WriteLine(mc["你要索引的字符下标"].属性); 
                Console.WriteLine(mc[0].属性);
            } 
      

  2.   

       。  public Student this[string name] 
       。 是呀,  我是这么做的, 有一个, bryant  我用了 不行, 不知为嘛, 索引器 重载不能成功,  汗,       一周了, 我就这么干的,  说清楚哇, 谢谢啦,  嘿嘿