mirror of
https://github.com/nsnail/spectre.console.git
synced 2025-06-19 13:28:16 +08:00

committed by
Patrik Svensson

parent
e280b82679
commit
1cf30f62fc
55
src/Spectre.Console/Internal/TypeConverterHelper.cs
Normal file
55
src/Spectre.Console/Internal/TypeConverterHelper.cs
Normal file
@ -0,0 +1,55 @@
|
||||
using System;
|
||||
using System.ComponentModel;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Reflection;
|
||||
|
||||
namespace Spectre.Console.Internal
|
||||
{
|
||||
internal static class TypeConverterHelper
|
||||
{
|
||||
public static string ConvertToString<T>(T input)
|
||||
{
|
||||
return GetTypeConverter<T>().ConvertToInvariantString(input);
|
||||
}
|
||||
|
||||
[SuppressMessage("Design", "CA1031:Do not catch general exception types")]
|
||||
public static bool TryConvertFromString<T>(string input, [MaybeNull] out T result)
|
||||
{
|
||||
try
|
||||
{
|
||||
result = (T)GetTypeConverter<T>().ConvertFromInvariantString(input);
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
result = default;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static TypeConverter GetTypeConverter<T>()
|
||||
{
|
||||
var converter = TypeDescriptor.GetConverter(typeof(T));
|
||||
if (converter != null)
|
||||
{
|
||||
return converter;
|
||||
}
|
||||
|
||||
var attribute = typeof(T).GetCustomAttribute<TypeConverterAttribute>();
|
||||
if (attribute != null)
|
||||
{
|
||||
var type = Type.GetType(attribute.ConverterTypeName, false, false);
|
||||
if (type != null)
|
||||
{
|
||||
converter = Activator.CreateInstance(type) as TypeConverter;
|
||||
if (converter != null)
|
||||
{
|
||||
return converter;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
throw new InvalidOperationException("Could not find type converter");
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user