【问题标题】:An unhandled exception of type 'System.IndexOutOfRangeException' C#'System.IndexOutOfRangeException' C# 类型的未处理异常
【发布时间】:2017-09-27 09:30:04
【问题描述】:

请帮助构建发布错误

    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: '索引超出了数组的范围。'

【问题讨论】:

  • 严重性代码说明项目文件行抑制状态警告无法读取状态文件“obj\Release\Runtime.csprojResolveAssemblyReference.cache”。找不到程序集“Microsoft.Build.Tasks.v12.0,版本=12.0.0.0,文化=中性,PublicKeyToken=b03f5f7f11d50a3a”。运行时
  • 所以.. 既然你不检查 args 长度,你希望每次启动程序时,都会传递参数?你确定 args[0] 和 args[1] 存在吗?如果在 VS 中启动,在调用 ToString() 之前,请确保调试和发布配置都设置了参数..

标签: c# .net


【解决方案1】:

乍一看,我会说,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 的评论

【讨论】:

  • 我认为“//做任何你喜欢的事情”有点极端,因为长度> 0,但正如评论中所添加的,你不应该在没有确保它们首先存在的情况下访问索引。所以我会检查所有预期的内容,或者最终将它们映射到字典或其他可以更清楚地了解正在发生的事情的对象
猜你喜欢
  • 2013-03-05
  • 2023-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-02
  • 1970-01-01
  • 2012-12-22
相关资源
最近更新 更多