Office中国论坛/Access中国论坛
标题:
【原创】再论:一维零基数组
[打印本页]
作者:
faunus
时间:
2014-2-24 11:23
标题:
【原创】再论:一维零基数组
本帖最后由 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();
}
}
}
复制代码
作者:
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