请高人给讲讲c#中索引器的作用和使用方法,最好能结合个例子
来源:学生作业帮 编辑:作业帮 分类:综合作业 时间:2024/10/04 05:40:44
请高人给讲讲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
麻烦采纳,谢谢!
麻烦采纳,谢谢!
请高人给讲讲c#中索引器的作用和使用方法,最好能结合个例子
C#构造函数的定义和在函数中的作用?举个例子就更好了
谁能给我讲讲语法?语法是什么?单词的顺序?那谁能给我讲讲...顺序?什么介词后面加什么等等的语法.最好能举个例子.我要升
good 最好能给个例子.
在C#中,作动词和名词用的“实例”,还有“实例化”分别是什么意思?最好分别举个例子啦,
请给我讲解一下,在英语中"in which……"是怎样的语法现象,如何翻译?最好能举个例子
引号的作用 给个例子
谁知道SNO4_N这种型号的接近开关的原理和用途?最好能给个例子说明下!
谁知道白盒测试中的分支条件覆盖和条件组合覆盖的区别,最好能给举个例子
怎样判断伴性遗传和非伴性遗传?最好能给个例子
C#中 #region和#endregion的作用?
化学中物质的微观和宏观到底是怎么区分的?最好能举个例子!