Non-zero based multidimensional arrays

折月煮酒 提交于 2020-06-25 02:15:07

问题


I am extracting cells out of a spreadsheet using the Interopt.Excel API. When I call:

object[,] rangeValues = (object[,])range.get_Value(XlRangeValueDataType.xlRangeValueDefault);

And set a breakpoint and inspect rangeValues, I see elements starting at [1,1] "foo", [1,2] "bar", etc.

However, if I do string[,] test = new string[2, 2] { { "one", "two" }, { "three", "four" } };

The elements start at [0,0]. How does the Excel API construct a multidimensional array w/ empty elements? I tried adding null but you still have an [0,0] entry. Their object doesn't show that.


回答1:


The CLR supports non-zero based arrays. They are confusing and to be avoided. I believe, the COM interop marshaller can create them.

http://msdn.microsoft.com/en-us/magazine/cc301755.aspx

Common Language Specification (CLS) compliance requires that all arrays be zero-based. This allows a method written in C# to create an array and pass the array's reference to code written in another language such as Visual Basic®. In addition, since zero-based arrays are by far the most common, Microsoft has spent a lot of time optimizing their performance. However, the CLR does support non-zero-based arrays but they are discouraged. For those of you who do not care about performance and cross-language portability, I will demonstrate how to create and use non-zero-based arrays later in this section.

This is the first time I have seen one in real-world code.

Apparently, multi-dimensional arrays have the same type no matter whether they are zero-based or not. Single-dimensional ones have a different type. Makes sense because if they had the same type the JIT would always have to produce slow code for the general case.

enter image description here



来源:https://stackoverflow.com/questions/23893343/non-zero-based-multidimensional-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!