我希望能够在 C# 中创建一个具有任意索引范围范围的数组,例如,一个索引为 100-115 的 16 元素数组。
C# 中的 native 数组是从 0 开始的,但有人告诉我(例如,在 Luaan 的评论 here 中),C# Array 类允许任意下限和上限。但在示例中,我看到 Array 类中的元素是通过 myArray.GetValue() 和 myArray.SetValue() 访问的,而不是像 myArray [ foo ]。
Array arr = Array.CreateInstance(typeof(string), new[]{16}, new[]{100});
Console.WriteLine(arr.Length); // 16
arr.SetValue("foo", 100);
Console.WriteLine(arr.GetValue(100)); // foo
有什么方法可以创建一个具有任意起始索引的数组,比如我可以在 C# 中使用传统 [ ] 语法访问的 [100]?
最佳答案
您可以创建一个实现装饰器模式的类:只需实现 IList 接口(interface)(也由 Array 实现)并在 this [int index] 属性上做任何您想要的移动。
装饰器模式描述如下: http://www.codeproject.com/Articles/479635/UnderstandingplusandplusImplementingplusDecoratorp
关于c# - 使用传统 [] 数组语法的 C# 中基于非 0 的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31348901/