41 行
1.6 KiB
C#
41 行
1.6 KiB
C#
namespace UndoTree;
|
|
|
|
internal static class UndoTreeOffset
|
|
{
|
|
public static bool TryAdd(Type type, object? current, object? from, object? to, out object? result)
|
|
{
|
|
result = null;
|
|
var underlying = Nullable.GetUnderlyingType(type) ?? type;
|
|
if (current is null || from is null || to is null || underlying.IsEnum)
|
|
return false;
|
|
|
|
try
|
|
{
|
|
if (underlying == typeof(TimeSpan))
|
|
{
|
|
result = (TimeSpan)current + ((TimeSpan)to - (TimeSpan)from);
|
|
return true;
|
|
}
|
|
|
|
switch (Type.GetTypeCode(underlying))
|
|
{
|
|
case TypeCode.Double or TypeCode.Single:
|
|
var sum = Convert.ToDouble(current) + (Convert.ToDouble(to) - Convert.ToDouble(from));
|
|
var converted = Convert.ChangeType(sum, underlying);
|
|
result = converted;
|
|
return double.IsFinite(sum) && double.IsFinite(Convert.ToDouble(converted));
|
|
case TypeCode.Decimal or TypeCode.SByte or TypeCode.Byte or TypeCode.Int16 or TypeCode.UInt16 or TypeCode.Int32 or TypeCode.UInt32 or TypeCode.Int64 or TypeCode.UInt64:
|
|
result = Convert.ChangeType(Convert.ToDecimal(current) + (Convert.ToDecimal(to) - Convert.ToDecimal(from)), underlying);
|
|
return true;
|
|
default:
|
|
return false;
|
|
}
|
|
}
|
|
catch (Exception exception) when (exception is OverflowException or InvalidCastException or FormatException)
|
|
{
|
|
result = null;
|
|
return false;
|
|
}
|
|
}
|
|
}
|