Skip to content
This repository was archived by the owner on Dec 24, 2022. It is now read-only.

Commit 9e981df

Browse files
committed
Change ConvertTo<T> to use DynamicNumber for converting from/to numeric types
1 parent e570efc commit 9e981df

File tree

1 file changed

+31
-3
lines changed

1 file changed

+31
-3
lines changed

src/ServiceStack.Text/AutoMappingUtils.cs

Lines changed: 31 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,16 +24,44 @@ public static T ConvertTo<T>(this object from)
2424
if (from == null)
2525
return default(T);
2626

27-
if (from.GetType() == typeof(T))
27+
var fromType = from.GetType();
28+
if (fromType == typeof(T))
2829
return (T)from;
2930

30-
if (from.GetType().IsValueType() || typeof(T).IsValueType())
31+
if (fromType.IsValueType() || typeof(T).IsValueType())
32+
{
33+
if (!fromType.IsEnum() && !typeof(T).IsEnum())
34+
{
35+
if (typeof(T) == typeof(char) && from is string s)
36+
return (T)(s.Length > 0 ? (object) s[0] : null);
37+
if (typeof(T) == typeof(string) && from is char c)
38+
return (T)(object)c.ToString();
39+
40+
var destNumberType = DynamicNumber.GetNumber(typeof(T));
41+
var value = destNumberType?.ConvertFrom(from);
42+
if (value != null)
43+
{
44+
if (typeof(T) == typeof(char))
45+
return (T)(object)value.ToString()[0];
46+
47+
return (T)value;
48+
}
49+
50+
if (typeof(T) == typeof(string))
51+
{
52+
var srcNumberType = DynamicNumber.GetNumber(from.GetType());
53+
if (srcNumberType != null)
54+
return (T)(object)srcNumberType.ToString(from);
55+
}
56+
}
57+
3158
return (T)ChangeValueType(from, typeof(T));
59+
}
3260

3361
if (typeof(IEnumerable).IsAssignableFromType(typeof(T)))
3462
{
3563
var listResult = TranslateListWithElements.TryTranslateCollections(
36-
from.GetType(), typeof(T), from);
64+
fromType, typeof(T), from);
3765

3866
return (T)listResult;
3967
}

0 commit comments

Comments
 (0)