C# Indexers Explained: Usage Guide
In C#, an indexer is a special property that allows objects to be accessed through indexing like an array. Indexers allow you to access elements of an object by providing a parameter, rather than through the object’s name. Indexers are commonly used to create data structures resembling arrays or collections, allowing for the retrieval or update of object values through indexing.
To use an indexer, you need to define a property in the class with the keyword “this”. Here is an example code:
public class MyCollection
{
private string[] data = new string[10];
public string this[int index]
{
get
{
return data[index];
}
set
{
data[index] = value;
}
}
}
In the example above, the MyCollection class has defined an indexer that allows access to the data in the class through integer indexing. This indexer can be used like an array.
MyCollection collection = new MyCollection();
collection[0] = "Hello";
collection[1] = "World";
Console.WriteLine(collection[0]); // 输出 Hello
Console.WriteLine(collection[1]); // 输出 World
By using indexers, the class usage can be more flexible, allowing access to elements within the class through indexes without needing to expose the class’s internal implementation.