我可以用 C# 创建只读索引器吗?

lac*_*chy 0 c#

这个 SO 问题中,我们了解如何为类创建索引器。是否可以为类创建只读索引器?

下面是微软提供的 Indexer 示例:

using System;

class SampleCollection<T>
{
   // Declare an array to store the data elements.
   private T[] arr = new T[100];

   // Define the indexer to allow client code to use [] notation.
   public T this[int i]
   {
      get { return arr[i]; }
      set { arr[i] = value; }
   }
}

class Program
{
   static void Main()
   {
      var stringCollection = new SampleCollection<string>();
      stringCollection[0] = "Hello, World";
      Console.WriteLine(stringCollection[0]);
   }
}
// The example displays the following output:
//       Hello, World.
Run Code Online (Sandbox Code Playgroud)

lac*_*chy 5

只读索引器可以通过set在索引器声明中不包含属性来实现。

修改微软的例子。

using System;

class ReadonlySampleCollection<T>
{
   // Declare an array to store the data elements.
   private T[] arr;

   // Constructor with variable length params.
   public ReadonlySampleCollection(params T[] arr) 
   {
       this.arr = arr;
   }

   // Define the indexer to allow client code to use [] notation.
   public T this[int i]
   {
      get { return arr[i]; }
   }
}

public class Program
{
   public static void Main()
   {
      var stringCollection = new ReadonlySampleCollection<string>("Hello, World");
      Console.WriteLine(stringCollection[0]);
      // stringCollection[0] = "Other world"; <<<< compiler error.
   }
}
// The example displays the following output:
//       Hello, World.
Run Code Online (Sandbox Code Playgroud)