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

How to overload operators in C#?

王林
Release: 2023-09-04 09:13:02
forward
986 people have browsed it

如何重载 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;
      }
   }
}
Copy after login

Output

A
B
C
D
E
F
G
H
I
J
Copy after login

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

Output

A
B
C
C
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template