Индексатор только для чтения может быть достигнут, если не включить свойство 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.