Home >Backend Development >C#.Net Tutorial >How to overload operators in C#?

How to overload operators in C#?

王林
王林forward
2023-09-04 09:13:02972browse

如何重载 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.

Example 1

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;
      }
   }
}

Output

A
B
C
D
E
F
G
H
I
J

Example 2

Rewrite []

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();
      }
   }
}

Output

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete