在C#中,CommandLineParser庫支持多種參數類型,包括基本的值類型、枚舉、集合等
int、float、double、bool、string等。List<T>、HashSet<T>、Dictionary<TKey, TValue>等。ICommandLineArgument接口來定義自己的參數類型。這里有一個簡單的例子,展示了如何使用CommandLineParser庫解析不同類型的參數:
using System;
using System.Collections.Generic;
using CommandLine;
public class Options
{
[Option('i', "integer", Required = true, HelpText = "An integer value.")]
public int IntegerValue { get; set; }
[Option('f', "float", Required = false, HelpText = "A float value.")]
public float FloatValue { get; set; }
[Option('s', "string", Required = false, HelpText = "A string value.")]
public string StringValue { get; set; }
[Option('b', "boolean", Required = false, HelpText = "A boolean value.")]
public bool BooleanValue { get; set; }
[Option('e', "enum", Required = false, HelpText = "An enumeration value.")]
public MyEnum EnumValue { get; set; }
[Option('l', "list", Required = false, HelpText = "A list of integers.")]
public IList<int> IntegerList { get; set; }
}
public enum MyEnum
{
Value1,
Value2,
Value3
}
class Program
{
static void Main(string[] args)
{
Parser.Default.ParseArguments<Options>(args)
.WithParsed(options =>
{
Console.WriteLine($"Integer: {options.IntegerValue}");
Console.WriteLine($"Float: {options.FloatValue}");
Console.WriteLine($"String: {options.StringValue}");
Console.WriteLine($"Boolean: {options.BooleanValue}");
Console.WriteLine($"Enum: {options.EnumValue}");
Console.WriteLine($"List: [{string.Join(", ", options.IntegerList)}]");
});
}
}
在這個例子中,我們定義了一個名為Options的類,其中包含了不同類型的屬性。然后,我們使用CommandLineParser庫解析命令行參數,并將結果存儲在Options對象中。最后,我們打印出解析后的參數值。