c# - 某些文本输入会导致数组超出范围
问题描述
我想解析 CommandLine
可以有两种格式:
command 123
- 带1
参数的命令 (123
)command 123,456
- 带2
参数的命令(123
和456
)
这里command
- 命令的名称,后跟空格' '
和参数:123
或123,456
以逗号分隔,
我试图用下面的代码来实现这个目标:
for (int i = 0; i <= CommandLine.TextLength; i++)
{
String[] CommandLineText = CommandLine.Text.Split(' ');
String Commands = CommandLine.Text.ToLower().Trim();
String Command = CommandLineText[0];
String Values = CommandLineText[1];
String[] Parameters = Values.Split(',');
int X = Int32.Parse(Parameters[0]);
int Y = Int32.Parse(Parameters[1]);
}
我遇到的问题是,当命令采用只有1
数字的第一种格式时,第二个参数变得out of bounds。
解决方案
假设您有一些命令需要 1 个参数,而其他命令需要 2 个......
您需要采取一些小步骤,以便您可以看到解析在什么时候出现故障。这也将允许您告诉用户错误的确切位置:
private void button1_Click(object sender, EventArgs e)
{
String rawCommand = CommandLine.Text.ToLower().Trim();
if (rawCommand.Length > 0)
{
String[] parts = rawCommand.Split(' ');
if (parts.Length >= 2)
{
String command = parts[0];
String[] args = parts[1].Split(',');
if (args.Length == 1)
{
String arg1 = args[0];
int X;
if (Int32.TryParse(arg1, out X))
{
// ... do something in here with "command" and "X" ...
Console.WriteLine("Command: " + command);
Console.WriteLine("X: " + X);
}
else
{
MessageBox.Show("Invalid X Argument!");
}
}
else if(args.Length >= 2)
{
String arg1 = args[0];
String arg2 = args[1];
int X, Y;
if (Int32.TryParse(arg1, out X) && Int32.TryParse(arg2, out Y))
{
// ... do something in here with "command" and "X" and "Y" ...
Console.WriteLine("Command: " + command);
Console.WriteLine("X: " + X);
Console.WriteLine("Y: " + Y);
}
else
{
MessageBox.Show("Invalid X and/or Y Argument!");
}
}
}
else
{
MessageBox.Show("Command has no Parameters!");
}
}
else
{
MessageBox.Show("Missing Command!");
}
}
推荐阅读
- amazon-web-services - 如何使用 vscode aws 扩展编辑 lambda (go)
- python - 如何在使用 Tomtom 进行地理编码时使用谷歌转换地理编码?(Python?
- python - 异常:AttributeError:“DefaultAzureCredential”对象没有使用 Azure Function 和 Python 的属性“signed_session”
- java - 我如何从界面中引用它
- flutter - 在自定义 Painter Flutter 中包装段落文本
- javascript - 通过 JS 应用多个 RegExp .match() 时如何阻止页面死机?
- sql - SQL Server 编写基于值的条件连接
- flutter - 如何在颤动中编辑数组中的元素
- amazon-web-services - 使用每个 terraform 将私有路由表附加到 NAT 网关
- html - 如何在 Outlook 桌面(Outlook 2007)中垂直对齐同一 TD 中的图像(标签内)和文本