C#中的索引超出范围异常? [英] Index Out Of Range Exception in C#?

查看:531
本文介绍了C#中的索引超出范围异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将VBA(MS Excel)中编码的程序转换为C#.
我一直收到IndexOutOfRange异常,尽管我认为没有可能的原因.

这是我在VBA中的代码的一个片段:

I am trying to convert a program coded in VBA (MS Excel) to C#.
I keep getting an IndexOutOfRange Exception, although I see no probable cause for it.

Here is a snippet of my code in VBA:

Dim gAGA8Xj(21) As Double
    gAGA8Xj(1) = Methane
    gAGA8Xj(2) = Nitrogen
    gAGA8Xj(3) = CarbonDioxide
    gAGA8Xj(4) = Ethane
    gAGA8Xj(5) = Propane
    gAGA8Xj(6) = Water
    gAGA8Xj(7) = HydrogenSulfide
    gAGA8Xj(8) = Hydrogen
    gAGA8Xj(9) = CarbonMonoxide
    gAGA8Xj(10) = Oxygen
    gAGA8Xj(11) = iButane
    gAGA8Xj(12) = nButane
    gAGA8Xj(13) = iPentane
    gAGA8Xj(14) = nPentane
    gAGA8Xj(15) = nHexane
    gAGA8Xj(16) = nHeptane
    gAGA8Xj(17) = nOctane
    gAGA8Xj(18) = nNonane
    gAGA8Xj(19) = nDecane
    gAGA8Xj(20) = Helium
    gAGA8Xj(21) = Argon



并在C#中:



and in C#:

double[] gAGA8Xj = new double[21];
gAGA8Xj[1] = Methane;
gAGA8Xj[2] = Nitrogen;
gAGA8Xj[3] = CarbonDioxide;
gAGA8Xj[4] = Ethane;
gAGA8Xj[5] = Propane;
gAGA8Xj[6] = Water;
gAGA8Xj[7] = HydrogenSulfide;
gAGA8Xj[8] = Hydrogen;
gAGA8Xj[9] = CarbonMonoxide;
gAGA8Xj[10] = Oxygen;
gAGA8Xj[11] = iButane;
gAGA8Xj[12] = nButane;
gAGA8Xj[13] = iPentane;
gAGA8Xj[14] = nPentane;
gAGA8Xj[15] = nHexane;
gAGA8Xj[16] = nHeptane;
gAGA8Xj[17] = nOctane;
gAGA8Xj[18] = nNonane;
gAGA8Xj[19] = nDecane;
gAGA8Xj[20] = Helium;
gAGA8Xj[21] = Argon;



我已经尝试了几乎所有我能想到的一切-将基本元素索引更改为0,更改数组的大小,添加索引为0的空元素,等等.

任何想法将不胜感激.
谢谢
Joleyn



I have tried pretty much everything I could think of - changing the base element index to 0, changing the size of the array, adding a null element indexed 0 etc.

Any ideas would be appreciated.
Thanks
Joleyn

推荐答案

数组从零开始.因此,索引应从零开始,以20结尾(总共21个元素).

编辑============

好的,我会为您说明:

Arrays are zero-based. Therefore, your index should start at zero and end at 20 (for a grand total of 21 elements).

EDIT ============

Okay, I''ll spell it out for you:

double[] gAGA8Xj = new double[21];
gAGA8Xj[0] = Methane;
... blah blah ...
gAGA8Xj[20] = Argon;


大小为21的数组只能处理最大索引20,因为数组是基于0的,所以yourArray [21]将导致崩溃.从0开始,最后一个条目应在索引20处.

希望这对您有帮助
An array of size 21 can only handle a max index of 20, as arrays are 0 based, so yourArray[21] is going to cause a smash. Start at 0 and your last entry should be at index 20.

Hope this helps


还假设您正确声明了所有其他变量.
(甲烷,氮气等为两倍)
There is also the assumption that you declared all the other variables correctly.
(Methane, nitrogen etc as double)


这篇关于C#中的索引超出范围异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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