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

C#程序通过Open with带参启动正常,直接运行报args索引越界如何解决

报错根因

无参数启动程序时,Main方法接收的args数组长度为0,不存在索引为0的元素,直接访问args[0]就会触发索引越界异常。你原本的判断逻辑是先访问元素再判断是否为null,但是无参数场景下这个元素根本不存在,判断逻辑还没执行就已经抛出异常了。

修复方案

先判断args数组的长度,确认有元素后再读取首个参数,修复后的代码如下:

static void Main(string[] args)
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    string inputPath = string.Empty;
    // 先判断数组是否有元素,再取值
    if (args.Length > 0)
    {
        // 额外兼容参数为null的异常场景
        inputPath = args[0] ?? string.Empty;
    }
    Application.Run(new Form1(inputPath));
}

内容的提问来源于stack exchange,提问作者A.Farahmand

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 15:45:02