C# what is the point or benefit of an indexer?

后端 未结 11 2109
暖寄归人
暖寄归人 2020-12-16 16:07

Doing some code reading and stumbled upon this snippet that I haven\'t seen before:

public SomeClass {
  public someInterface this[String strParameter] {
            


        
11条回答
  •  甜味超标
    2020-12-16 16:25

    In my opinion, it's just a syntax convenience. Where would you NOT use it:

    public SomeClass {
      private int[] nums;
      public GetVal this[int ind] {
        get {
          return nums[ind]; // this is pointless since array is already indexed
        }
      }
    }
    

    Where would you benefit from it:

    public Matrix {
      private Dictionary matrixData; // Matrix indecies, value
      public double this[int row, int col] {
        get {
          return matrixData[string.Format("{0},{1}", row, col)];
        }
      }
    }
    

    As you can see, for some reason, your data is a Dictionary indexed with a string key and you wish to call this with two integer indecies and still do not want to change your data type:

    Matrix m = new Matrix();
    ...
    Console.WriteLine( m[1,2] );
    

提交回复
热议问题