Office中国论坛/Access中国论坛

标题: 【原创】再论:一维零基数组 [打印本页]

作者: faunus    时间: 2014-2-24 11:23
标题: 【原创】再论:一维零基数组
本帖最后由 faunus 于 2014-2-24 11:24 编辑

零基,即: zero-based, 最小索引为0
CLR对一维零基数组使用了特殊的IL操作指令newarr,
在访问数组时不需要通过索引减去偏移量来完成,
而且JIT也只需执行一次范围检查,
可以大大提升访问性能。

  1. using System;
  2. using System.Collections.Generic;
  3. namespace ConsoleApplication8
  4. {
  5.     internal class Program
  6.     {
  7.         private static void Main(string[] args)
  8.         {
  9.             int[] length = new int[] { 2 };
  10.             int[] startIndex = new int[] { 4 };
  11.             Array nonZeroBased = Array.CreateInstance(typeof(string), length, startIndex);
  12.             nonZeroBased.SetValue("first", 4);
  13.             nonZeroBased.SetValue("second", 5);
  14.             Console.WriteLine(nonZeroBased.GetValue(4)); // "first"
  15.             Console.WriteLine(nonZeroBased.GetValue(5)); // "second"
  16.             //转换到接口
  17.             IEnumerable<string> ieT = (IEnumerable<string>)nonZeroBased;
  18.             ICollection<string> icT = (ICollection<string>)nonZeroBased;
  19.             IList<string> icL = (IList<string>)nonZeroBased;
  20.             //!!注意,必须进行强制性转换,天知道转完后是个什么模样了
  21.             //转化为接口后,就有定义
  22.             icL.Insert(0, "test");
  23.             icL.Remove("first");
  24.             icL.RemoveAt(4);
  25.             //未处理的异常:  System.InvalidCastException:
  26.             //无法将类型为“System.String[*]”的对象强制转换为类型“System.Collections.Generic.IEnumerable`1[System.String]”。
  27.             int[,] intArray = { { 1, 2 }, { 1, 2 }, { 1, 2 } };
  28.             //转换到接口
  29.             //IEnumerable<int> ieT2 = (IEnumerable<int>)intArray;
  30.             //ICollection<int> icT2 = (ICollection<int>)intArray;
  31.             //IList<int> icL2 = (IList<int>)intArray;
  32.             //!!注意,强制转换都不成
  33.             Console.ReadKey();
  34.         }
  35.     }
  36. }
复制代码




作者: faunus    时间: 2014-2-24 11:23
看来同样是数组,地位还很不一样:
关于接口转换的总结如下:
[1]一维零基数组
可(隐式)转成接口
Ilist上三函调用情况:
//未处理的异常:  System.NotSupportedException: 集合的大小是固定的。
//在 System.SZArrayHelper.Xxx[T](...)

[2]一维非零基数组
可(显式)转成接口
Ilist上三函调用情况:
//未处理的异常:  System.InvalidCastException:
//无法将类型为“System.String[*]”的对象强制转换为
//类型“System.Collections.Generic.IEnumerable`1[System.String]”。

[3]非一维数组(交差数组没测,有兴趣的朋友可以试一下)
不可转成接口
当然也不存在三函调用情况




欢迎光临 Office中国论坛/Access中国论坛 (http://www.office-cn.net/) Powered by Discuz! X3.3