System.IndexOutOfRangeException:索引超出范围

时间:2014-02-14 15:35:11

标签: c#

我在C#中有一个程序,当我在Visual Studio中运行它时可以正常工作。

但是当我运行文件时,我在main中出现错误。

错误是:

未处理的异常:System.IndexOutOfRangeException:索引超出了数组的范围

我的主要人物: 错误位于 int tala = convert.toInt32 ...

namespace MultiplicationTable
{
    class Program
    {
        static void Main(string[] args)
        {
            int tala = Convert.ToInt32(args[0]);
            MultiplicationTable test = new MultiplicationTable(tala);
            Console.ReadLine();
        }
    }
}

有什么想法吗?

2 个答案:

答案 0 :(得分:6)

问题:当您从Visual Studio运行它时,您提供了参数,但是当您通过双击直接运行程序时,您无法提供参数,因为它将直接调用。

解决方案:您需要正确提供命令行参数,请按照以下步骤从命令行运行程序

第1步:转到命令提示符

第2步:转到你的程序exe文件路径

步骤3:现在通过提供如下命令行参数来执行程序:

c:\myprogrampath\program.exe 12

尝试此代码以避免例外:

if(args.Length>0)
{
    int tala = Convert.ToInt32(args[0]);
    MultiplicationTable test = new MultiplicationTable(tala);
    Console.ReadLine();
}
else
{
    Console.WriteLine("No Command Line Arguments - Quiting");
}

答案 1 :(得分:-1)

是,

如前所述的海报,要么你必须将参数传递给你的程序,要么你必须检查,如果args不是null而使用if语句并且“捕获”这个错误。

if(args) {
//here your code
}

或者,您可以尝试try-catch语句:

try {
   //here you read the arguments and pass to a variable
}
catch(System.IndexOutOfRangeException) {
     //other codepart
}