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

问题描述 投票:0回答:1

this SO question中,我们看到了如何为类创建索引器。是否可以为一个类创建一个只读索引器?

这里是Microsoft提供的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.
c#
1个回答
2
投票

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

要修改Microsoft示例。

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.
© www.soinside.com 2019 - 2024. All rights reserved.