10
10
using System . Runtime . Serialization ;
11
11
using System . Threading ;
12
12
using ServiceStack . Text ;
13
+ using ServiceStack . Text . Common ;
13
14
14
15
namespace ServiceStack
15
16
{
@@ -24,14 +25,10 @@ public static T ConvertTo<T>(this object from)
24
25
return default ( T ) ;
25
26
26
27
if ( from . GetType ( ) == typeof ( T ) )
27
- {
28
28
return ( T ) from ;
29
- }
30
29
31
- if ( from . GetType ( ) . IsValueType ( ) )
32
- {
33
- return ( T ) Convert . ChangeType ( from , typeof ( T ) , provider : null ) ;
34
- }
30
+ if ( from . GetType ( ) . IsValueType ( ) || typeof ( T ) . IsValueType ( ) )
31
+ return ( T ) ChangeValueType ( from , typeof ( T ) ) ;
35
32
36
33
if ( typeof ( IEnumerable ) . IsAssignableFromType ( typeof ( T ) ) )
37
34
{
@@ -45,6 +42,40 @@ public static T ConvertTo<T>(this object from)
45
42
return to . PopulateWith ( from ) ;
46
43
}
47
44
45
+ public static object ConvertTo ( this object from , Type type )
46
+ {
47
+ if ( from == null )
48
+ return null ;
49
+
50
+ if ( from . GetType ( ) == type )
51
+ return from ;
52
+
53
+ if ( from . GetType ( ) . IsValueType ( ) || type . IsValueType ( ) )
54
+ return ChangeValueType ( from , type ) ;
55
+
56
+ if ( typeof ( IEnumerable ) . IsAssignableFromType ( type ) )
57
+ {
58
+ var listResult = TranslateListWithElements . TryTranslateCollections (
59
+ from . GetType ( ) , type , from ) ;
60
+
61
+ return listResult ;
62
+ }
63
+
64
+ var to = type . CreateInstance ( ) ;
65
+ return to . PopulateInstance ( from ) ;
66
+ }
67
+
68
+ private static object ChangeValueType ( object from , Type type )
69
+ {
70
+ var strValue = from as string ;
71
+ if ( type == typeof ( DateTime ) && strValue != null )
72
+ return DateTimeSerializer . ParseShortestXsdDateTime ( strValue ) ;
73
+ if ( from is DateTime )
74
+ return DateTimeSerializer . ToShortestXsdDateTimeString ( ( DateTime ) from ) ;
75
+
76
+ return Convert . ChangeType ( from , type , provider : null ) ;
77
+ }
78
+
48
79
private static readonly Dictionary < Type , List < string > > TypePropertyNamesMap = new Dictionary < Type , List < string > > ( ) ;
49
80
50
81
public static List < string > GetPropertyNames ( this Type type )
@@ -266,6 +297,18 @@ public static To PopulateWith<To, From>(this To to, From from)
266
297
return to ;
267
298
}
268
299
300
+ public static object PopulateInstance ( this object to , object from )
301
+ {
302
+ if ( to == null || from == null )
303
+ return null ;
304
+
305
+ var assignmentDefinition = GetAssignmentDefinition ( to . GetType ( ) , from . GetType ( ) ) ;
306
+
307
+ assignmentDefinition . PopulateWithNonDefaultValues ( to , from ) ;
308
+
309
+ return to ;
310
+ }
311
+
269
312
public static To PopulateWithNonDefaultValues < To , From > ( this To to , From from )
270
313
{
271
314
if ( Equals ( to , default ( To ) ) || Equals ( from , default ( From ) ) ) return default ( To ) ;
0 commit comments