c# - 向 Main (string [] args) 提供输入时出错
问题描述
我有一个程序将通过“打开方式...”菜单运行,并将路径文件作为程序的输入。我的代码如下:
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
if (args[0] != null)
{
Application.Run(new Form1(args[0]));
}
else
{
Application.Run(new Form1(""));
}
}
当给输入程序时它会正确运行,但是当我在没有输入的情况下输入程序时,通常会出现以下错误:
System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'
有没有办法解决这个问题?
解决方案
检查args
不为空:
if(args.Any())
{
// use args[0] here
....
}
else
{
....
}
您遇到的错误意味着它args
是空的,因此访问第一个元素(在 0 索引处)是非法的。
推荐阅读
- lua - lua 将字符串转换为数字
- java - 如何计算列表中出现的次数并将它们与项目匹配?
- amazon-web-services - 在线公开您的 AWS ACCESS_KEY_ID 是否安全?
- go - IPX 网络与 DOS 和 DOSBox(在 Raspbian 下)
- sql-server - 左连接顺序在 linq 查询(EF Core 2)中是否重要?
- javascript - 以 dd/mm/yyyy 格式对 Javascript 中的日期进行排序
- algorithm - 确定图的传递自反闭包的时间复杂度
- css - “您必须自己安装对等依赖项。”从克隆 GitHub 链接导入天气图标时显示
- python - 有多少国家组织了不止一届奥运会?使用 python 熊猫
- python - 使用 psycopg2 插入大量数据无法正常工作