- 不依赖第三方包
- 解析命令行参数
- 支持选项、子命令
- 核心使用反射
- 安装.NET SDK8.x
- 添加nuget包
dotnet add package Cracker.CommandLine
or
Install-Package Cracker.CommandLine -Version 1.0.3
- 示例Program.cs
var app = new CommandApp();
app.Add<ConvertCommand>("convert")
.Child(() => new CommandConfiguration("ts", new TimeToTimestampCommand()).WithDescription("时间戳转时间"))
.Child(() => new CommandConfiguration("time", new TimestampToTimeCommand()).WithDescription("时间转时间戳"))
.WithDescription("格式转换");
await app.StartAsync(args);
- 示例ConvertCommand.cs
public class ConvertCommand : CommandBase
{
public override Task ExecuteAsync(CommandContext context)
{
return Task.CompletedTask;
}
}
public class TimeParameter
{
[CliArgument(0, "要转换的时间|时间戳", true)]
public string? Value { get; set; }
[CliOption("-f", "指定时间戳的格式,可选值:<s|ms>,s:秒,ms:毫秒", "s")]
public string? Format { get; set; }
}
public class TimeToTimestampCommand : CommandBase<TimeParameter>
{
public override Task ExecuteAsync(CommandContext context)
{
if (DateTime.TryParse(Receive.Value, out var time))
{
if (Receive.Format == "s")
{
Console.WriteLine(TimeUtils.DateTimeToTimestamp(time, true));
}
else
{
Console.WriteLine(TimeUtils.DateTimeToTimestamp(time, false));
}
}
else
{
Console.WriteLine("时间格式错误");
}
return Task.CompletedTask;
}
}
public class TimestampToTimeCommand : CommandBase<TimeParameter>
{
public override Task ExecuteAsync(CommandContext context)
{
if (long.TryParse(Receive.Value, out var ts))
{
Console.WriteLine(TimeUtils.TimestampToDateTime(ts).ToString("yyyy-MM-dd HH:mm:ss"));
}
else
{
Console.WriteLine("时间戳格式错误");
}
return Task.CompletedTask;
}
}
QQ: 1491184849
MySite: https://crackerwork.cn
您也可以在贡献者名单中参看所有参与该项目的开发者。
该项目签署了MIT 授权许可,详情请参阅 LICENSE.txt