类型为“System.IndexOutOfRangeException”的未处理异常C#

时间:2017-09-27 09:30:04

标签: c# .net

请帮助构建发布错误

    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();
        }
    }
}

显示错误

  

抛出异常:Runtime.exe中的'System.IndexOutOfRangeException'   发生了'System.IndexOutOfRangeException'类型的未处理异常   在Runtime.exe中,索引超出了数组的范围。

     

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

第25行错误 System.IndexOutOfRangeException:'索引超出了数组的范围。'

1 个答案:

答案 0 :(得分: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)
}

编辑:更改//do whatever you like以解决rmjoia的评论