1
1
using System ;
2
+ using System . Collections ;
2
3
using System . Collections . Generic ;
3
4
using System . Diagnostics ;
4
5
using System . Linq ;
@@ -55,5 +56,51 @@ public static void SetDefaults(this object target, object defaults, params strin
55
56
}
56
57
}
57
58
}
59
+
60
+ [ DebuggerHidden ]
61
+ public static void SetFrom ( this object target , object source , params string [ ] ignoreProperties )
62
+ {
63
+ if ( target == null || source == null )
64
+ {
65
+ return ;
66
+ }
67
+ Type targetType = target . GetType ( ) ;
68
+ Type sourceType = source . GetType ( ) ;
69
+ IEnumerable < PropertyInfo > sourceProperties = sourceType . GetProperties ( BindingFlags . GetProperty | BindingFlags . Instance | BindingFlags . Public )
70
+ . Where ( x => x . CanRead && ! ignoreProperties . Contains ( x . Name ) ) ;
71
+ foreach ( PropertyInfo sourceProperty in sourceProperties )
72
+ {
73
+ PropertyInfo targetProperty = targetType . GetProperty ( sourceProperty . Name , /*BindingFlags.GetProperty | BindingFlags.SetProperty |*/ BindingFlags . Instance | BindingFlags . Public ) ;
74
+ if ( targetProperty == null )
75
+ {
76
+ continue ;
77
+ }
78
+ object sourceValue = sourceProperty . GetGetMethod ( ) . Invoke ( source , null ) ;
79
+ if ( targetProperty . CanWrite )
80
+ {
81
+ targetProperty . GetSetMethod ( ) . Invoke ( target , new [ ] { sourceValue } ) ;
82
+ }
83
+ else if ( targetProperty . CanRead && typeof ( IList ) . IsAssignableFrom ( targetProperty . PropertyType ) )
84
+ {
85
+ IList list = ( IList ) targetProperty . GetGetMethod ( ) . Invoke ( target , null ) ;
86
+ list . Clear ( ) ;
87
+ if ( sourceValue is IEnumerable enumerable )
88
+ {
89
+ foreach ( object entry in enumerable )
90
+ {
91
+ list . Add ( entry ) ;
92
+ }
93
+ }
94
+ }
95
+ else if ( targetProperty . CanRead && ! targetProperty . PropertyType . IsValueType )
96
+ {
97
+ object targetValue = targetProperty . GetGetMethod ( ) . Invoke ( target , null ) ;
98
+ if ( targetValue != null && sourceValue != null )
99
+ {
100
+ targetValue . SetFrom ( sourceValue ) ;
101
+ }
102
+ }
103
+ }
104
+ }
58
105
}
59
106
}
0 commit comments