using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
namespace PCL.Core.App.Cli;
///
/// 无泛型的命令行参数模型
///
///
public abstract class CommandArgument
{
///
/// 参数键
///
public required string Key { get; init; }
///
/// 参数值文本
///
public required string ValueText { get; init; }
///
/// 参数值类型
///
public abstract ArgumentValueKind ValueKind { get; }
///
/// 尝试以指定类型获取参数值
///
/// 参数值,若尝试失败则为该类型默认值
/// 参数值的类型
/// 是否成功,若类型不匹配则失败
public abstract bool TryCastValue([NotNullWhen(true)] out T? value);
public T? CastValue()
{
var result = TryCastValue(out T? value);
return result ? value : throw new InvalidCastException("Value type mismatch or cannot cast");
}
}
///
/// 命令行参数模型
///
/// 参数值的类型
public abstract class CommandArgument : CommandArgument
{
///
/// 从参数值文本中解析参数类型
///
/// 对应类型的参数值
protected abstract TValue ParseValueText();
private bool _isValueParsed = false;
///
/// 参数值
///
public TValue Value
{
get
{
if (_isValueParsed) return field;
_isValueParsed = true;
return field = ParseValueText();
}
protected init
{
field = value;
_isValueParsed = true;
}
} = default!;
public override bool TryCastValue([NotNullWhen(true)] out T value)
{
if (Value is T v)
{
value = v;
return true;
}
value = default!;
if (typeof(T) == typeof(string))
{
Unsafe.As(ref value) = ValueText;
#pragma warning disable CS8762 // The analyzer sucks.
return true;
#pragma warning restore CS8762
}
return false;
}
}