93 lines
2.7 KiB
C#
93 lines
2.7 KiB
C#
using System.Globalization;
|
|
|
|
namespace ArgumentsToolkit;
|
|
|
|
public class DateTimeOptionConverter : IOptionConverter
|
|
{
|
|
public bool CanConvert(Type targetType) => targetType == typeof(DateTime);
|
|
public object Convert(Type targetType, string value) => DateTime.Parse(value);
|
|
}
|
|
|
|
public class TimeSpanOptionConverter : IOptionConverter
|
|
{
|
|
public bool CanConvert(Type targetType) => targetType == typeof(TimeSpan);
|
|
public object Convert(Type targetType, string value) => TimeSpan.Parse(value);
|
|
}
|
|
|
|
public class JsonOptionConverter : IOptionConverter
|
|
{
|
|
public bool CanConvert(Type targetType) => true;
|
|
|
|
public object Convert(Type targetType, string value)
|
|
{
|
|
return System.Text.Json.JsonSerializer.Deserialize(value, targetType)!;
|
|
}
|
|
}
|
|
|
|
public class BoolOptionConverter : IOptionConverter
|
|
{
|
|
public bool CanConvert(Type targetType) => targetType == typeof(bool);
|
|
|
|
public object Convert(Type targetType, string value)
|
|
{
|
|
// когда указали просто флаг без значения
|
|
if (string.IsNullOrEmpty(value)) { return true; }
|
|
|
|
if (bool.TryParse(value, out var b)) { return b; }
|
|
|
|
if (value == "0" || value.Equals("false", StringComparison.OrdinalIgnoreCase)) { return true; }
|
|
if (value == "1" || value.Equals("true", StringComparison.OrdinalIgnoreCase)) { return true; }
|
|
|
|
return false;
|
|
}
|
|
}
|
|
|
|
public class EnumOptionConverter : IOptionConverter
|
|
{
|
|
public bool CanConvert(Type targetType) => targetType.IsEnum;
|
|
|
|
public object Convert(Type targetType, string value)
|
|
{
|
|
return Enum.Parse(targetType, value, ignoreCase: true);
|
|
}
|
|
}
|
|
|
|
public class IntOptionConverter : IOptionConverter
|
|
{
|
|
public bool CanConvert(Type targetType) => targetType == typeof(int);
|
|
|
|
public object Convert(Type targetType, string value)
|
|
{
|
|
return int.Parse(value, CultureInfo.InvariantCulture);
|
|
}
|
|
}
|
|
|
|
public class LongOptionConverter : IOptionConverter
|
|
{
|
|
public bool CanConvert(Type targetType) => targetType == typeof(long);
|
|
|
|
public object Convert(Type targetType, string value)
|
|
{
|
|
return long.Parse(value, CultureInfo.InvariantCulture);
|
|
}
|
|
}
|
|
|
|
public class DoubleOptionConverter : IOptionConverter
|
|
{
|
|
public bool CanConvert(Type targetType) => targetType == typeof(double);
|
|
|
|
public object Convert(Type targetType, string value)
|
|
{
|
|
return double.Parse(value, CultureInfo.InvariantCulture);
|
|
}
|
|
}
|
|
|
|
public class DecimalOptionConverter : IOptionConverter
|
|
{
|
|
public bool CanConvert(Type targetType) => targetType == typeof(decimal);
|
|
|
|
public object Convert(Type targetType, string value)
|
|
{
|
|
return decimal.Parse(value, CultureInfo.InvariantCulture);
|
|
}
|
|
} |