System.IndexOutOfRangeException:索引超出范围

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

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

错误是:

未处理的exception: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(); } } } 

有任何想法吗?

问题:当您从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"); } 

是,

如前所说的海报,要么你必须将参数传递给你的程序,要么你必须检查,如果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 }