我想決議 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。
uj5u.com熱心網友回復:
看來你想要這樣的東西:
using System.Linq;
....
string CommandLine = "doIt 123,456";
....
// Given Command Line we split it by space into two parts:
// 0. command name
// 1. command arguments
string[] parts = CommandLine
.ToLower()
.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries);
// 1st part is a command name
command = parts[0];
// 2nd part (if any) is parameters
int[] Parameters = parts.Length <= 1
? new int[0] // We don't have parameters
: parts[1]
.Split(',') // Split by comma
.Select(item => int.Parse(item)) // Parse each argument as int
.ToArray(); // Organize them as an array
如果你堅持擁有X并且Y你必須確保它Parameters足夠長:
// let X = -1 if Parameters doesn't have it
int X = Parameters.Length >= 1 ? Parameters[0] : -1;
// let Y = -1 if Parameters doesn't have it
int Y = Parameters.Length >= 2 ? Parameters[1] : -1;
uj5u.com熱心網友回復:
假設您有一些命令需要 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!");
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/364388.html
上一篇:嘗試從文本框中決議多行
