Sicherung
This commit is contained in:
69
Config.Net/TypeParsers/DefaultParser.cs
Normal file
69
Config.Net/TypeParsers/DefaultParser.cs
Normal file
@@ -0,0 +1,69 @@
|
||||
using System;
|
||||
using System.Reflection;
|
||||
|
||||
namespace Config.Net.TypeParsers
|
||||
{
|
||||
class DefaultParser
|
||||
{
|
||||
public bool TryParse(string? value, Type t, out object? result)
|
||||
{
|
||||
if(IsEnum(t))
|
||||
{
|
||||
if(value == null)
|
||||
{
|
||||
result = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
result = Enum.Parse(t, value, true);
|
||||
return true;
|
||||
}
|
||||
catch(ArgumentException)
|
||||
{
|
||||
|
||||
}
|
||||
catch(OverflowException)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
result = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public bool IsSupported(Type t)
|
||||
{
|
||||
return IsEnum(t);
|
||||
}
|
||||
|
||||
public string? ToRawString(object? value)
|
||||
{
|
||||
if(value == null) return null;
|
||||
|
||||
Type t = value.GetType();
|
||||
|
||||
if(IsEnum(t))
|
||||
{
|
||||
return value.ToString();
|
||||
}
|
||||
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
static bool IsEnum(Type t)
|
||||
{
|
||||
if(t == null) return false;
|
||||
|
||||
//try to get the underlying type if this is a nullable type
|
||||
Type? nullable = Nullable.GetUnderlyingType(t);
|
||||
if(nullable != null) t = nullable;
|
||||
|
||||
return t.GetTypeInfo().IsEnum;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user