如何在C#中的1维数组索引从1开始 [英] How to create a 1-Dimensional Array in C# with index starting at 1

查看:528
本文介绍了如何在C#中的1维数组索引从1开始的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关多维数组Array.CreateInstance可以用来创建非从零开始的索引数组,但是如果你尝试,对于一个一维数组(向量),如例如:

For multidimensional arrays Array.CreateInstance can be used to create non-zero index based arrays, but if you try that for a 1-dimensional arrays (vectors) as in e.g.:

public double[] myArray = (double[])Array.CreateInstance(typeof(double), new int[1] { 12 }, new int[1] { 1 });

这将在运行时从多维数组要转换成一维数组失败,失败

this will fail at run-time when the cast from the the multidimensional Array to a single-dimensional array fails

"Unable to cast object of type 'System.Double[*]' to type 'System.Double[]'"

现在我可以只创建一个零基于阵列并忽略第一个值,或偏移等工作,但我俯瞰一些C#语法魔力,允许基于非零矢量?

Now I could just create a zero based array and ignore the first value, or work with offsets etc., but am I overlooking some c# syntactic magic that allows for non zero based vectors?

更新:

如果他说我要埃里克利珀的的话<一个href=\"http://stackoverflow.com/questions/955732/c-nonzero-based-arrays-are-not-cls-compliant\">There's没有明显的方式,使在C#中一个非零基于阵列

I'll take Eric Lippert's word for it if he says "There's no obvious way to make a non-zero-based array in C#"

推荐答案

在C#中所有的数组都是从零开始的。据我所知是没有办法创造一个1基于阵列。想象一下,什么样的乱七八糟的都不会发生,如果这是可能的。这里有一个类似的线程这就解释更多的细节问题 - C#:非零基于阵列不符合CLS

All arrays in C# are zero based. As far as I know there is no way to create a 1 based array. Imagine what kind of a mess would have happened if that was possible. Here is a similar thread which explains the issue with more details - C#: Nonzero-based arrays are not CLS-compliant

这篇关于如何在C#中的1维数组索引从1开始的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆