You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

未传全可选参数时C#控制台应用抛出System.IndexOutOfRangeException的解决

解决方案

核心问题分析

你遇到的IndexOutOfRangeException根源是控制台应用构造函数里硬编码访问固定索引的命令行参数(比如Environment.GetCommandLineArgs()[21]),当传入参数数量不足时直接触发索引越界。同时Main方法内的循环逻辑存在错误(如无意义的b+11索引),进一步加剧了问题。

控制台应用代码重构

彻底重构参数处理逻辑,放弃硬编码固定索引的方式,改用动态判断参数数量:

using System;

namespace CNCOnline_OPC_DA
{
    class Program
    {
        private const int MaxItemCount = 20;
        static string[] item_array;

        static void Main(string[] args)
        {
            // 1. 基础参数校验:必须传入项数量和至少一个项
            if (args.Length < 2)
            {
                Console.Error.WriteLine("错误:必须传入项数量和至少一个项参数");
                Environment.Exit(1);
            }

            // 2. 解析并验证项数量
            if (!int.TryParse(args[1], out int itemCount) || itemCount < 1 || itemCount > MaxItemCount)
            {
                Console.Error.WriteLine($"错误:项数量必须是1到{MaxItemCount}之间的有效整数");
                Environment.Exit(1);
            }

            // 3. 验证传入的项参数数量是否达标
            if (args.Length - 2 < itemCount)
            {
                Console.Error.WriteLine($"错误:传入的项参数数量不足{itemCount}个");
                Environment.Exit(1);
            }

            // 4. 初始化项数组并填充有效数据
            item_array = new string[MaxItemCount];
            // 填充实际传入的项
            for (int b = 0; b < itemCount; b++)
            {
                item_array[b] = args[2 + b];
            }
            // 剩余未使用位置填充空字符串,兼容原有业务逻辑
            for (int b = itemCount; b < MaxItemCount; b++)
            {
                item_array[b] = string.Empty;
            }

            // 剩余业务代码...
        }
    }
}

父应用代码简化

现在父应用只需传入项数量和实际需要的项参数,无需补多余的x:

Process Process_OPCDA = new Process
{
    StartInfo = new ProcessStartInfo
    {
        FileName = TagService_MTX.MTX_OPC_DA_reader_path,
        Arguments = "3 item1 item2 item3", // 仅传实际需要的参数
        UseShellExecute = false,
        RedirectStandardOutput = true,
        CreateNoWindow = true
    }
};
Process_OPCDA.Start();

关键优化点

  • 移除构造函数中硬编码的参数访问,彻底避免初始化阶段的索引越界异常
  • 增加完整的参数合法性校验,提前向调用方反馈明确的错误信息
  • 动态读取实际传入的项参数,剩余数组位置自动填充空字符串,兼容原有业务逻辑
  • 直接使用Main方法的args数组处理参数,比Environment.GetCommandLineArgs()更简洁高效

内容的提问来源于stack exchange,提问作者Mdarende

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 12:50:06