dotnet-types/PoweredSoft.Types/Convert.cs

57 lines
1.6 KiB
C#
Raw Normal View History

2018-04-17 22:16:22 -04:00
using PoweredSoft.Types.Converters;
using PoweredSoft.Types.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
namespace PoweredSoft.Types
{
public static class Converter
{
public static List<ITypeConverter> Converters { get; internal set; } = new List<ITypeConverter>
{
new StringToDateConverter(),
new StringToGuidConverter()
};
public static void RegisterConverter(ITypeConverter converter)
{
lock (Converters)
{
Converters.Add(converter);
}
}
public static void ReplaceConverter(ITypeConverter converter, Type source, Type destination)
{
lock (Converters)
{
Converters.RemoveAll(t => t.CanConvert(source, destination));
Converters.Add(converter);
}
}
public static object To(this object source, Type type)
{
object ret = null;
// safe if null.
if (source == null)
return ret;
// establish final type.
var notNullType = Nullable.GetUnderlyingType(type);
var finalType = notNullType ?? type;
var converter = Converters.FirstOrDefault(t => t.CanConvert(source.GetType(), finalType));
if (converter != null)
ret = converter.Convert(source, finalType);
else
ret = Convert.ChangeType(source, finalType);
return ret;
}
}
}