如何创建自定义类型以始终表示具有一定数量的元素的某些基本类型的数组
本文关键字:类型 元素 数组 具有一 表示 创建 何创建 自定义 | 更新日期: 2023-09-27 18:36:01
>我想知道我如何创建这种可能的类型。这个想法是有一个类型,该类型表示仅包含 3 个元素的整数数组,但可以使用括号访问,就像任何普通数组一样。
我本质上是想转换
int[] myArray = new int[3];
到
myType myArray = new myType();
然后访问 myArray,就像它是使用原始 int[] 进程创建的一样:
myArray[0] = 1;
myArray[1] = 2;
myArray[2] = 3;
这可能吗?
可以将索引器添加到任何对象。 例如(直接来自 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
是一种常见的替代方法。