请高人给讲讲c#中索引器的作用和使用方法,最好能结合个例子

来源:学生作业帮助网 编辑:作业帮 时间:2024/04/29 22:20:48

请高人给讲讲c#中索引器的作用和使用方法,最好能结合个例子
请高人给讲讲c#中索引器的作用和使用方法,最好能结合个例子

请高人给讲讲c#中索引器的作用和使用方法,最好能结合个例子
实例+索引的方法来访问类成员. using System; class MyTest { public static int Main() { SchoolMate myMate=new SchoolMate(); Console.WriteLine(myMate.linkman[0]); //直接访问成员 //以索引器的形式访问成员 Console.WriteLine("name:{0}",myMate[0]); Console.WriteLine("Enter your name:"); myMate[0]=Console.ReadLine(); Console.WriteLine("name:{0}",myMate[0]); Console.WriteLine("sex:{0}",myMate[1]); Console.WriteLine("age:{0}",myMate[2]); return 0; } } class SchoolMate { public string[] linkman; public SchoolMate() { linkman=new string[]{"yesline","male","23"}; } public string this[int index] //string指返回值,this指类,或此类创建的实例. { get { return linkman[index]; } set { linkman[index]=value; } } } 在此成员中,访问linkman数组当然可以用另外的方法,如访问第一个成员:myMate.linkman[0]. 既然可以这样,为什么要用索引器呢?书上说当类是容器时用索引器有用,可我还没看到此类例子. 可以重载索引器.如再定义一个索引器: public int othertest=23; //定义 public int this[string index] //index的类型不能在为int,因为已定义过 { get{return othertest;} set{othertest=value;} } //使用,查看结果: Console.WriteLine(myMate["1"]); //myMate[""]中所以可以为任意string //输出:23
麻烦采纳,谢谢!