-
Notifications
You must be signed in to change notification settings - Fork 291
Mapping Properties To Options
You can map almost any data type to command line option.
Scalar values are mapped using OptionAttribute type. Let's define a string option.
class Options
{
[Option("p", "person-to-greet", DefaultValue="World")]
public string PersonToGreet { get; set; }
}
Everything passed to -p
or --person-to-great
option will be loaded into Options::PersonToGreat
instance property. This option is not required (default Required = false
), so if not specified the property will contain the string "World".
Both app -p Jhonny
and app --person-to-great Jhonny
will be accepted.
You can map without problems also enum and nullable values:
enum GreetType
{
Hello,
Bye,
Regards
}
class Options
{
[Option("g", "greet-type")]
public GreetType SpecifiedGreetType { get; set; }
[Option("t", "times-to-greet")]
public int? TimesToGreet { get; set; }
}
When specifying enum values, you don't need to respect case. Both app -g bye
and app --greet-type REGARDS
are allowed.
To map an array you need to use OptionArrayAttribute type as in following sample:
class Options
{
[OptionArray("v", "values", DefaultValue=new double[] {.1, .2, .3})]
public double[] Temperatures { get; set; }
}
You can even specify a default when working with array. All values specified after an OptionArray will be loaded into the array.
$ app -v 1.9 2.3 5.3 12.4 9.1334
$ app --values 192.9 .3 1.23 .324 3.3323
The parser is culture-sensitive. If you like to subordinate the parsing process to particular culture, just change the current thread culture:
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");