Хабр Курсы для всех
РЕКЛАМА
Практикум, Хекслет, SkyPro, авторские курсы — собрали всех и попросили скидки. Осталось выбрать!
var p = new OptionSet () {
{ "n|name=", "the name of someone to greet.",
v => names.Add (v) },
{ "r|repeat=", "the number of times to repeat the greeting.",
(int v) => repeat = v },
{ "v", "increase debug message verbosity",
v => { if (v != null) ++verbosity; } },
{ "h|help", "show this message and exit",
v => show_help = v != null },
}
string data = null;
bool help = false;
int verbose = 0;
var p = new OptionSet () {
{ "file=", v => data = v },
{ "v|verbose", v => { ++verbose } },
{ "h|?|help", v => help = v != null },
};
List<string> extra = p.Parse (args);
Все вроде бы хорошо, но чем больше параметров, тем больше появляется строк типа
int num = int.Parse(args[Х]);
где Х это номер параметра.
чем больше параметров, тем больше появляется строк
Откуда в программе вообще строки берутся? Вроде не должно быть.
Когда параметров сильно меньше, чем 100500 (всегда), можно просмотреть свитчем параметры, что там оно передалося, и что из этого нужно взять. Да, появится много немного строк, но мне нравится — когда параметры прибиты гвоздями к программе и к документации.
Вот, как простой пример к осуждению экспертами:
private static string switch_on { get; set; } = "";
private static int timeOut { get; set; }
private static int interVal { get; set; }
private static bool isDebug { get; set; } = false;
private static IReadOnlyCollection<string> ProfileInfo { get; set; } private static void Main(string[] margs)
{
if (margs.Length > 0)
{
Console.WriteLine("This app startet with parameter/s");
for (int i = 0; i < margs.Length; i++)
{
switch_on = margs[i];
switch (switch_on)
{
case "-d":
Console.WriteLine("Case Debug");
isDebug = true;
break;
case "-t":
Console.WriteLine("Case Timeout");
timeOut = int.Parse(margs[++i]);
break;
case "-p":
Console.WriteLine("Case Profile");
// profile info write with starts and ands " char`s, whitespace char - is a separator of profile info items
ProfileInfo = new List<string>(margs[++i].Trim(new char[] { '"' }).Split(new char[] { ' ' }));
break;
case "-i":
Console.WriteLine("Case Interval");
interVal= int.Parse(margs[++i]);
break;
default: Console.WriteLine("Case Default"); break;
}
Console.WriteLine($"Arg {i} = {margs[i]}");
}
}
Console.WriteLine($"Args length = {margs.Length}");
Console.WriteLine($"Debug = {isDebug}");
Console.WriteLine($"Timeout = {timeOut}");
Console.WriteLine($"Interval = {interVal}");
Console.WriteLine($"Profile info = {SummaryProfileInfo(ProfileInfo)}");
Console.ReadLine();
}Теперь я могу передать параметры "-d -p "Юра Морозов" -i 555 -t 3600", в любом порядке, в любом наборе, и всё пройдёт гладко. Нет?
Работа с Command Line в .Net