2017-09-27 97 views
0

請幫助建立發佈錯誤類型的 'System.IndexOutOfRangeException' C#未處理的異常

using System; 
using System.Collections.Generic; 
using System.Globalization; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Timers; 

namespace Runtime 
{ 
    class Program 
    { 
     static Timer timer; 
     static string date = ""; 
     static string time = ""; 
     static void Main(string[] args) 
     { 
      date = args[0].ToString(); 


      time = args[1].ToString(); 
      schedule_Timer(); 
      Console.ReadLine(); 

     } 

     static void schedule_Timer() 
     { 
      Console.WriteLine("### Timer Started ###"); 

      DateTime nowTime = DateTime.Now; 
      DateTime scheduledTime = DateTime.ParseExact(date + " " + time, "yyyy-MM-dd HH:mm", new CultureInfo("en-US")); 
      //if (nowTime > scheduledTime) 
      //{ 
      // return; 
      //} 


      double tickTime = (double)(scheduledTime - DateTime.Now).TotalMilliseconds; 

      timer = new System.Timers.Timer(tickTime); 
      timer.Elapsed += new ElapsedEventHandler(timer_Elapsed); 
      timer.Enabled = true; 
      timer.Start(); 

     } 


     static void timer_Elapsed(object sender, ElapsedEventArgs e) 
     { 
      Console.WriteLine("### Timer Stopped ### \n"); 
      timer.Stop(); 
      Console.WriteLine("### Scheduled Task Started ### \n\n"); 
      Console.WriteLine("Do - Performing scheduled task\n"); 
      Console.WriteLine("### Task Finished ### \n\n"); 
      //---------------------------------------------------------------- 


      //schedule_Timer(); 
     } 
    } 
} 

顯示錯誤

拋出異常: 'System.IndexOutOfRangeException' 在Runtime.exe的 未處理的異常類型'System.IndexOutOfRangeException'在Runtime.exe中發生 索引超出了數組的範圍。

程序'[7172] Runtime.exe'已退出,代碼爲-1(0xffffffff)。

25行錯誤 System.IndexOutOfRangeException:'索引超出了數組的範圍'。

+0

嚴重\t代碼\t說明\t項目\t文件\t線\t抑制狀態 警告\t \t無法讀取狀態文件「OBJ \發佈\運行。 csprojResolveAssemblyReference.cache」。無法找到程序集'Microsoft.Build.Tasks.v12.0,版本= 12.0.0.0,Culture = neutral,PublicKeyToken = b03f5f7f11d50a3a'。 \t運行時 –

+1

所以..因爲你沒有檢查參數長度,你期望每次程序啓動時,參數都通過?你確定args [0]和args [1]存在嗎?如果在VS中啓動,請在調用ToString() 之前,請確保調試和發佈配置都具有參數設置。 – rmjoia

回答

0

乍一看我會說,args[]不包含任何或只有1個元素。 你應該在訪問它之前添加一個支票。

if (args == null) 
{ 
    if (args.Length > 0) // or for your specific case: (args.Length >= 2) 
     //do your stuff (including further appropriate checks) 
} 

編輯:爲了解決rmjoia的評論改變//do whatever you like

+0

我認爲「//做任何你喜歡的事情」有點極端,只是因爲長度> 0,但作爲在評論中添加的時候,你不應該在沒有確定它們先存在的情況下訪問索引..所以我只需檢查所有預期的內容,或者最終將它們映射到字典或其他對象,以便更清楚地瞭解正在發生的事情 – rmjoia

相關問題