是否可以使用?將命令列輸入直接系結到NodaTime.Duration(或System.TimeSpan)System.CommandLine?也許通過在某處提供自定義轉換器?
static void Main(string[] args)
{
var rootCommand = new RootCommand
{
new Option<Duration>("--my-duration"),
};
rootCommand.Handler = CommandHandler.Create(
(Duration myDuration) => { Console.WriteLine(myDuration); });
rootCommand.InvokeAsync(args);
}
uj5u.com熱心網友回復:
我沒有做過System.CommandLine多少作業,關于自定義決議的檔案也不多,但我相信你想要的是ParseArgument<T>. 幸運的是,在 NodaTime 上撰寫一個擴展方法IPattern<T>來創建它的實體相當容易。
這是一個沒有經過徹底測驗的擴展方法:
using NodaTime.Text;
using System.CommandLine.Parsing;
namespace Demo
{
public static class PatternExtensions
{
public static ParseArgument<T> ToParseArgument<T>(this IPattern<T> pattern) =>
result => ParseResult<T>(pattern, result);
private static T ParseResult<T>(IPattern<T> pattern, ArgumentResult result)
{
// TODO: Check whether Tokens is actually what we want to use.
if (result.Tokens.Count != 1)
{
result.ErrorMessage = "Only a single token can be parsed";
return default;
}
var token = result.Tokens[0];
var nodaResult = pattern.Parse(token.Value);
if (nodaResult.Success)
{
return nodaResult.Value;
}
else
{
result.ErrorMessage = nodaResult.Exception.Message;
return default;
}
}
}
}
以及使用它的代碼:
using NodaTime;
using NodaTime.Text;
using System;
using System.CommandLine;
using System.CommandLine.Invocation;
using Demo; // To make the extension method available
class Program
{
static void Main(string[] args)
{
var rootCommand = new RootCommand
{
new Option<Duration>(
"--my-duration",
DurationPattern.JsonRoundtrip.ToParseArgument()),
};
rootCommand.Handler = CommandHandler.Create(
(Duration myDuration) => Console.WriteLine(myDuration));
rootCommand.Invoke(args);
}
}
被決議的模式 ( DurationPattern.JsonRoundtrip) 使用“小時數”作為最重要的部分,而默認格式(Console.WriteLine在本例中使用的)使用“天數”,因此很容易判斷它確實在決議:
$ dotnet run -- --my-duration=27:23:45
1:03:23:45
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/323416.html
