using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication12 { enum Genders { Boy, Girl } struct Student { private int math; public int chinese; public int englist; public Genders gender; public int Math { get { return this.math; } set { this.math = value; } } public int this[string Index] { get { switch (Index) { case "数学": return this.math; case "语文": return this.chinese; case "英语": return this.englist; default: return -1; } } } public Student(int math, int chinese, int english, Genders gender) { this.math = math; this.chinese = chinese; this.englist = english; this.gender = gender; } public double Aver() { int sum = this.englist + this.chinese + this.math; return sum / 3.0; } } class Program { static void Main(string[] args) { Student lili = new Student(65,80,91,Genders.Girl); double avg = lili.Aver(); Console.WriteLine("lili's math is{0}",lili["数学"]); Console.WriteLine("lili's averger is {0:0.00},shi is a {1}",avg,lili.gender); Console.ReadKey(); } } } 【运行结果】 lili's math is65 lili's averger is 78.67,shi is a Girl 索引器:把对象当数组使用 using System; using System.Collections.Generic; using System.Text; namespace Index { public class Clazz { string[] name = { "皮蛋","门神","小强","宝宝"}; public string this[int 座位号] { set { this.name[座位号 ] = value; } get { return this.name[座位号]; } } } class Program { static void Main(string[] args) { Clazz c = new Clazz(); //把对象c当数组使用 Console.WriteLine("{0}", c[0]); Console.WriteLine("{0}", c[1]); Console.WriteLine("{0}", c[2]); Console.WriteLine("{0}", c[3]); Console.WriteLine("======================="); c[0] = "机器人"; Console.WriteLine("{0}", c[0]); Console.WriteLine("{0}", c[1]); Console.WriteLine("{0}", c[2]); Console.WriteLine("{0}", c[3]); Console.ReadKey(); } } } 【运行结果】 皮蛋 门神 小强 宝宝 ======================= 机器人 门神 小强 宝宝