How to use the C# index indicator
This article mainly explains "how to use the C# index indicator". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought. Let's study and learn how to use the C# index indicator.
The C# index indicator is not difficult to use. They are used in the same way as arrays. Within a class, you can manage a collection of data as you wish. These objects can be a limited collection of class members, another array, or complex data structures. Regardless of the internal implementation of the class, its data can be obtained by using the C# index indicator.
A class that implements a C # index indicator (indexer) can use its instantiated objects like an array, but unlike an array, the parameter type of the C # index indicator is not limited to int. In a nutshell, it is essentially an attribute with parameters:
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
}
/ / override the ToString method to facilitate output
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
}
}
/ / implement index accessor
Public Point this [int Index]
{
Get
{
Return points [Index]
}
}
}
/ / Thank you watson hua (http://huazhihao.cnblogs.com/) for your guidance
/ / Index indicator is essentially an attribute with parameters, and parameters are not limited to int.
Class WeatherOfWeek
{
Public string this [int Index]
{
Get
{
/ / Note that the case segment is returned directly using return, so there is no need for 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
/ / the standard writing method of 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