The indexer is similar to the attribute, but only for arrays. The example of using the indexer is as follows:
namespace ConsoleApplication9Indexer{ class Class1 { private string[] Strs = new string[100]; public string this[int i] { get { return Strs[i]; } set { Strs[i] = value; } } private int[,] Ints = new int[10,10]; public int this[int i,int j] { get { return Ints[i,j]; } set { Ints[i,j] = value; } } } class Program { static void Main(string[] args) { Class1 Tc = new Class1(); Tc[1] = "sjkf"; Console.WriteLine(Tc[1]); Tc[0,0] = 10; Console.WriteLine(Tc[0,0]); } }}
Features:
<1> use this keyword to define the Indexer
<2> access with get and set
<3> the index can be accessed by the indexer according to custom rules rather than integers.
<4> The indexer can be overloaded.
<5> The indexer can have multiple parameters.
Reasoning:
<1> only one indexer with the same parameter type can exist in the class.
<2> If there are multiple different indexers, the parameters of the indexer must be different.
Interface Indexer
The interface indexer cannot use an access modifier or a function body;
When the class inherits multiple interface indexers and the parameters of the indexer are the same, you need to explicitly implement the interface indexer. The use of the final indexer can only be called through interfaces, it cannot be called directly through class objects, for example:
namespace ConsoleApplication9Indexer{ public interface Inter1 { string this[int i] { get; set; } } public interface Inter2 { string this[int j] { get; set; } } public interface Inter3 { string this[int i] { get; set; } } class Class2 : Inter1,Inter2,Inter3 { private string[] names = new string[100]; private string[] sexs = new string[100]; private string[] Adds = new string[100]; string Inter1.this[int i] { get { return names[i]; } set { names[i] = value; } } string Inter2.this[int j] { get { return sexs[j]; } set { sexs[j] = value; } } public string this[int i] { get { return Adds[i]; } set { Adds[i] = value; } } }static void Main(string[] args) { Class2 Ts = new Class2(); Inter1 Inters1 = (Inter1)Ts; Inters1[11] = "whjhd"; Console.WriteLine(Inters1[11]); Inter2 Inters2 = (Inter2)Ts; Inters2[67] = "what a fucking day"; Console.WriteLine(Inters2[67]);}}