实例+索引的方法来访问类成员。
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[""]中
实例+索引的方法来访问类成员。
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。
版权保护: 本文由《C语法小知识(六)属性与索引器》原创,转载请保留链接: http://www.xqdyishu.cn/shkpxzs/73921.html