|
本帖最后由 faunus 于 2014-2-24 11:24 编辑
零基,即: zero-based, 最小索引为0
CLR对一维零基数组使用了特殊的IL操作指令newarr,
在访问数组时不需要通过索引减去偏移量来完成,
而且JIT也只需执行一次范围检查,
可以大大提升访问性能。
- using System;
- using System.Collections.Generic;
- namespace ConsoleApplication8
- {
- internal class Program
- {
- private static void Main(string[] args)
- {
- int[] length = new int[] { 2 };
- int[] startIndex = new int[] { 4 };
- Array nonZeroBased = Array.CreateInstance(typeof(string), length, startIndex);
- nonZeroBased.SetValue("first", 4);
- nonZeroBased.SetValue("second", 5);
- Console.WriteLine(nonZeroBased.GetValue(4)); // "first"
- Console.WriteLine(nonZeroBased.GetValue(5)); // "second"
- //转换到接口
- IEnumerable<string> ieT = (IEnumerable<string>)nonZeroBased;
- ICollection<string> icT = (ICollection<string>)nonZeroBased;
- IList<string> icL = (IList<string>)nonZeroBased;
- //!!注意,必须进行强制性转换,天知道转完后是个什么模样了
- //转化为接口后,就有定义
- icL.Insert(0, "test");
- icL.Remove("first");
- icL.RemoveAt(4);
- //未处理的异常: System.InvalidCastException:
- //无法将类型为“System.String[*]”的对象强制转换为类型“System.Collections.Generic.IEnumerable`1[System.String]”。
- int[,] intArray = { { 1, 2 }, { 1, 2 }, { 1, 2 } };
- //转换到接口
- //IEnumerable<int> ieT2 = (IEnumerable<int>)intArray;
- //ICollection<int> icT2 = (ICollection<int>)intArray;
- //IList<int> icL2 = (IList<int>)intArray;
- //!!注意,强制转换都不成
- Console.ReadKey();
- }
- }
- }
复制代码
|
|