在C#項(xiàng)目中,您可以使用CommandLineParser
庫(kù)來(lái)解析命令行參數(shù)
CommandLineParser
庫(kù)。在項(xiàng)目的根目錄下打開(kāi)終端或命令提示符,然后運(yùn)行以下命令:dotnet add package CommandLineParser
Options.cs
的新類(lèi)文件,并定義要解析的命令行選項(xiàng):using CommandLine;
namespace YourNamespace
{
public class Options
{
[Option('f', "file", Required = true, HelpText = "Input file to be processed.")]
public string InputFile { get; set; }
[Option('o', "output", Required = false, HelpText = "Output file path.")]
public string OutputFile { get; set; }
[Option('v', "verbose", Required = false, HelpText = "Set output to verbose messages.")]
public bool Verbose { get; set; }
}
}
Program.cs
文件中,使用CommandLineParser
解析命令行參數(shù):using System;
using CommandLine;
namespace YourNamespace
{
class Program
{
static void Main(string[] args)
{
Parser.Default.ParseArguments<Options>(args)
.WithParsed(options =>
{
Console.WriteLine($"Input file: {options.InputFile}");
Console.WriteLine($"Output file: {options.OutputFile}");
Console.WriteLine($"Verbose: {options.Verbose}");
})
.WithNotParsed(errors =>
{
foreach (var error in errors)
{
Console.WriteLine(error);
}
});
}
}
}
dotnet run -- -f input.txt -o output.txt -v
這將輸出:
Input file: input.txt
Output file: output.txt
Verbose: True
dotnet run -- -o output.txt -v
這將輸出:
Required option 'f, file' is missing.
通過(guò)這種方式,您可以測(cè)試CommandLineParser
在C#項(xiàng)目中的功能。