设为首页收藏本站Access中国

Office中国论坛/Access中国论坛

 找回密码
 注册

QQ登录

只需一步,快速开始

返回列表 发新帖
查看: 2357|回复: 1
打印 上一主题 下一主题

【原创】再论:一维零基数组

[复制链接]
跳转到指定楼层
1#
发表于 2014-2-24 11:23:28 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
本帖最后由 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. }
复制代码



分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 分享分享 分享淘帖 订阅订阅
2#
 楼主| 发表于 2014-2-24 11:23:39 | 只看该作者
看来同样是数组,地位还很不一样:
关于接口转换的总结如下:
[1]一维零基数组
可(隐式)转成接口
Ilist上三函调用情况:
//未处理的异常:  System.NotSupportedException: 集合的大小是固定的。
//在 System.SZArrayHelper.Xxx[T](...)

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

[3]非一维数组(交差数组没测,有兴趣的朋友可以试一下)
不可转成接口
当然也不存在三函调用情况
您需要登录后才可以回帖 登录 | 注册

本版积分规则

QQ|站长邮箱|小黑屋|手机版|Office中国/Access中国 ( 粤ICP备10043721号-1 )  

GMT+8, 2024-5-7 18:28 , Processed in 0.094656 second(s), 25 queries .

Powered by Discuz! X3.3

© 2001-2017 Comsenz Inc.

快速回复 返回顶部 返回列表