在C#中如何实现索引器?
我按照书上的内容作了,可是,那个,用字符串做的索引不能识别:下面贴出部分代码,希望各位大虾指点下,谢谢啦, 嘿嘿
//索引器所在的类。
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
谢谢大家了, 困扰我很久了呀,