Home >Backend Development >C#.Net Tutorial >How to overload operators in C#?
The [] operator is called an indexer.
Indexers allow indexing of objects, such as arrays. When you define an indexer for a class, the class behaves like a virtual array. You can then access instances of that class using the array access operator ([ ]).
Indexers can be overloaded. Indexers can also declare multiple parameters, and each parameter can be of a different type. The index does not necessarily have to be an integer.
static void Main(string[] args){ IndexerClass Team = new IndexerClass(); Team[0] = "A"; Team[1] = "B"; Team[2] = "C"; Team[3] = "D"; Team[4] = "E"; Team[5] = "F"; Team[6] = "G"; Team[7] = "H"; Team[8] = "I"; Team[9] = "J"; for (int i = 0; i < 10; i++){ Console.WriteLine(Team[i]); } Console.ReadLine(); } class IndexerClass{ private string[] names = new string[10]; public string this[int i]{ get{ return names[i]; } set { names[i] = value; } } }
A B C D E F G H I J
static class Program{ static void Main(string[] args){ IndexerClass Team = new IndexerClass(); Team[0] = "A"; Team[1] = "B"; Team[2] = "C"; for (int i = 0; i < 10; i++){ Console.WriteLine(Team[i]); } System.Console.WriteLine(Team["C"]); Console.ReadLine(); } } class IndexerClass{ private string[] names = new string[10]; public string this[int i]{ get{ return names[i]; } set{ names[i] = value; } } public string this[string i]{ get{ return names.Where(x => x == i).FirstOrDefault(); } } }
A B C C
The above is the detailed content of How to overload operators in C#?. For more information, please follow other related articles on the PHP Chinese website!