C#语言有很多值得学习的地方,这里我们主要介绍C#索引指示器,包括介绍C#索引指示器并不难使用。它们的用法跟数组相同等方面。
C#索引指示器并不难使用。它们的用法跟数组相同。在一个类内部,你可以按照你的意愿来管理一组数据的集合。这些对象可以是类成员的有限集合,也可以是另外一个数组,或者是一些复杂的数据结构。不考虑类的内部实现,其数据可以通过使用C#索引指示器来获得。
实现C#索引指示器(indexer)的类可以象数组那样使用其实例后的对象,但与数组不同的是C#索引指示器的参数类型不仅限于int。简单来说,其本质就是一个含参数属性:
- using System;
- using System.Collections.Generic;
- using System.Text;
- namespace Example08
- {
- public class Point
- {
- private double x, y;
- public Point(double X, double Y)
- {
- x = X;
- y = Y;
- }
- //重写ToString方法方便输出
- public override string ToString()
- {
- return String.Format("X: {0} , Y: {1}", x, y);
- }
- }
- public class Points
- {
- Point[] points;
- public Points(Point[] Points)
- {
- points = Points;
- }
- public int PointNumber
- {
- get
- {
- return points.Length;
- }
- }
- //实现索引访问器
- public Point this[int Index]
- {
- get
- {
- return points[Index];
- }
- }
- }
- //感谢watson hua(http://huazhihao.cnblogs.com/)的指点
- //索引指示器的实质是含参属性,参数并不只限于int
- class WeatherOfWeek
- {
- public string this[int Index]
- {
- get
- {
- //注意case段使用return直接返回所以不需要break
- switch (Index)
- {
- case 0:
- {
- return "Today is cloudy!";
- }
- case 5:
- {
- return "Today is thundershower!";
- }
- default:
- {
- return "Today is fine!";
- }
- }
- }
- }
- public string this[string Day]
- {
- get
- {
- string TodayWeather = null;
- //switch的标准写法
- switch (Day)
- {
- case "Sunday":
- {
- TodayWeather = "Today is cloudy!";
- break;
- }
- case "Friday":
- {
- TodayWeather = "Today is thundershower!";
- break;
- }
- default:
- {
- TodayWeather = "Today is fine!";
- break;
- }
- }
- return TodayWeather;
- }
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
- Point[] tmpPoints = new Point[10];
- for (int i = 0; i < tmpPoints.Length; i++)
- {
- tmpPoints[i] = new Point(i, Math.Sin(i));
- }
- Points tmpObj = new Points(tmpPoints);
- for (int i = 0; i < tmpObj.PointNumber; i++)
- {
- Console.WriteLine(tmpObj[i]);
- }
- string[] Week = new string[]
{ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Staurday"};- WeatherOfWeek tmpWeatherOfWeek = new WeatherOfWeek();
- for (int i = 0; i < 6; i++)
- {
- Console.WriteLine(tmpWeatherOfWeek[i]);
- }
- foreach (string tmpDay in Week)
- {
- Console.WriteLine(tmpWeatherOfWeek[tmpDay]);
- }
- Console.ReadLine();
- }
- }
- }
【编辑推荐】