Skip to content

Instantly share code, notes, and snippets.

@devlights
Last active December 18, 2018 05:16
Show Gist options
  • Save devlights/0503d01d097e2ad495572d91a4d423f3 to your computer and use it in GitHub Desktop.
Save devlights/0503d01d097e2ad495572d91a4d423f3 to your computer and use it in GitHub Desktop.
[C#] コマンドラインオプションを扱う (CommandLine ライブラリ)
using System;
using CommandLine;
namespace CommandLineArg
{
class Program
{
public class Options
{
// shortnameで短いオプション名。(-v)longnameで長いオプション名を指定できる。(--versioninfo)
// デフォルトでlongnameは指定していない場合はプロパティ名を小文字にして "--"が先頭についた
// ものになる。(VersionInfo の場合は --versioninfo となる。)
[Option('v', "versioninfo", Required = false, HelpText = "バージョン情報")]
public bool VersionInfo { get; set;}
}
static void Main(string[] args)
{
// --------------------------------------------------------
// https://github.com/commandlineparser/commandline
//
// C# でコマンドラインオプションを扱うためのライブラリ
// --------------------------------------------------------
// (1) ライブラリがオプションの値を設定するためのデータクラスを定義
// (2) Parser.Default.ParseArguments メソッドで解析
// --------------------------------------------------------
Parser
.Default
.ParseArguments<Options>(args)
.WithParsed<Options>(o =>
{
if (o.VersionInfo)
{
Console.WriteLine("1.0.0");
}
});
}
}
}
@devlights
Copy link
Author

$ dotnet new console --name CommandLineArg
$ dotnet add package CommandLineParser
$ dotnet build
$ dotnet run

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment