如何创建自定义类型以始终表示具有一定数量元素的某种基本类型的数组?

How can I create a custom type to always represent an array of some basic type with a set number of elements?

我想知道如何创建这种可能的类型。我们的想法是拥有一个表示仅包含 3 个元素的整数数组的类型,但可以像任何普通数组一样使用方括号访问。

我基本上想转换

int[] myArray = new int[3];

进入

myType myArray = new myType();

然后访问 myArray,就像它是使用原始 int[] 进程创建的一样:

myArray[0] = 1;
myArray[1] = 2;
myArray[2] = 3;

这可能吗?

您可以add an indexer任何对象。例如(直接来自 MSDN):

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

    // Define the indexer, which will allow client code 
    // to use [] notation on the class instance itself. 
    // (See line 2 of code in Main below.)         
    public T this[int i]
    {
        get
        {
            // This indexer is very simple, and just returns or sets 
            // the corresponding element from the internal array. 
            return arr[i];
        }
        set
        {
            arr[i] = value;
        }
    }
}

请注意,该对象在内部管理一个包含 100 个元素的数组。在您的情况下,您只需使用 3 个元素。该对象的用法将类似于您要查找的内容:

// Declare an instance of the SampleCollection type.
SampleCollection<string> stringCollection = new SampleCollection<string>();

// Use [] notation on the type.
stringCollection[0] = "Hello, World";
System.Console.WriteLine(stringCollection[0]);

另请注意,索引器 明确地 定义为示例中的 int。您也可以为索引器使用其他类型。 (string 是一个常见的替代方案。)