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

Commit b3d4b65

Browse files
committed
Check for implicit casts in ConvertTo
1 parent e9a159c commit b3d4b65

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

src/ServiceStack.Text/AutoMappingUtils.cs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,10 @@ public static object ConvertTo(this object from, Type toType, bool skipConverter
157157
if (fromType.IsValueType || toType.IsValueType)
158158
return ChangeValueType(from, toType);
159159

160+
var mi = GetImplicitCastMethod(fromType, toType);
161+
if (mi != null)
162+
return mi.Invoke(null, new[] { from });
163+
160164
if (from is string str)
161165
return TypeSerializer.DeserializeFromString(str, toType);
162166
if (from is ReadOnlyMemory<char> rom)
@@ -191,6 +195,14 @@ public static MethodInfo GetImplicitCastMethod(Type fromType, Type toType)
191195
return mi;
192196
}
193197
}
198+
foreach (var mi in toType.GetMethods(BindingFlags.Public | BindingFlags.Static))
199+
{
200+
if (mi.Name == "op_Implicit" && mi.ReturnType == toType &&
201+
mi.GetParameters().FirstOrDefault()?.ParameterType == fromType)
202+
{
203+
return mi;
204+
}
205+
}
194206
return null;
195207
}
196208

@@ -204,6 +216,14 @@ public static MethodInfo GetExplicitCastMethod(Type fromType, Type toType)
204216
return mi;
205217
}
206218
}
219+
foreach (var mi in fromType.GetMethods(BindingFlags.Public | BindingFlags.Static))
220+
{
221+
if (mi.Name == "op_Explicit" && mi.ReturnType == toType &&
222+
mi.GetParameters().FirstOrDefault()?.ParameterType == fromType)
223+
{
224+
return mi;
225+
}
226+
}
207227
return null;
208228
}
209229

tests/ServiceStack.Text.Tests/AutoMappingTests.cs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
using System.Linq;
55
using System.Linq.Expressions;
66
using System.Runtime.Serialization;
7+
using System.Xml.Linq;
78
#if !NETCORE
89
using System.Web.Script.Serialization;
910
#endif
@@ -1150,6 +1151,13 @@ public void Can_convert_between_structs_with_implicit_casts()
11501151
Assert.That(b.Id, Is.EqualTo(a.Id));
11511152
}
11521153

1154+
[Test]
1155+
public void Can_convert_from_class_implicit_Casts()
1156+
{
1157+
var to = "test".ConvertTo<XName>();
1158+
Assert.That(to.LocalName, Is.EqualTo("test"));
1159+
}
1160+
11531161
struct C
11541162
{
11551163
public int Id { get; }

0 commit comments

Comments
 (0)