C#索引指示器淺析
作者:佚名
這里介紹C#索引指示器并不難使用。它們的用法跟數組相同。在一個類內部,你可以按照你的意愿來管理一組數據的集合。
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();
- }
- }
- }
【編輯推薦】
責任編輯:佚名
來源:
賽迪網