第六章 数组和索引器 (6.6 索引器)
生活随笔
收集整理的這篇文章主要介紹了
第六章 数组和索引器 (6.6 索引器)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
【案例】本案例在Student類中定義索引器,然后通過stu[i]?來引用Student類的對象實例。
【案例目的】(1)掌握索引器定義與使用。
?(2)理解索引器與屬性的區別。
【代碼】
namespace Example1 {class Program{static void Main(string[] args){Student stu = new Student();//stu是Student類的對象名stu.Sno = "1840";stu.Name = "李四";stu[0] = 89; //stu[下標]表示類的索引器stu[1] = 90;Console.WriteLine("學生{0},學號{1}",stu.Name, stu.Sno);Console.WriteLine("他的第一門成績是{0},第二門成績是{1}", stu[0], stu[1]);Console.ReadLine();}}public class Student{private string sno;private string name;private double[] scores;public string Sno//屬性 {set { sno = value; }get { return sno; }}public string Name{set { name = value; }get { return name; }}public Student(){scores = new double[10];} public double this[int index] //定義索引器 { get{if(index<0||index>=scores.Length ){return 0;}else{return scores[index];}}set{if (!(index < 0 || index >= scores.Length)){scores[index] = value;}}} } }運行結果:
?
【索引器拓展案例與分析】
?
轉載于:https://www.cnblogs.com/programme-maker/p/10668516.html
總結
以上是生活随笔為你收集整理的第六章 数组和索引器 (6.6 索引器)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 东北话十级经典语录骂人(东北骂人最狠的脏
- 下一篇: 【小记】-006--关于高度塌陷的问题