@@ -242,37 +242,69 @@ internal static void Clone<TModel>(this TModel source, TModel item)
242242 /// Creates an instance of a type and ensures all class-type properties are initialized.
243243 /// </summary>
244244 /// <typeparam name="TItem">The type to create an instance of.</typeparam>
245+ /// <param name="isAutoInitializeModelProperty">Whether to automatically initialize model properties default value is false.</param>
245246 /// <returns>An instance of the specified type with initialized properties.</returns>
246- public static TItem CreateInstanceWithCascade < TItem > ( )
247+ public static TItem ? CreateInstanceWithCascade < TItem > ( bool isAutoInitializeModelProperty = false )
247248 {
248- var instance = Activator . CreateInstance < TItem > ( ) ;
249- instance ! . EnsureInitialized ( ) ;
249+ TItem ? instance ;
250+ try
251+ {
252+ instance = Activator . CreateInstance < TItem > ( ) ;
253+ if ( isAutoInitializeModelProperty )
254+ {
255+ instance . EnsureInitialized ( isAutoInitializeModelProperty ) ;
256+ }
257+ }
258+ catch
259+ {
260+ throw ;
261+ }
262+ return instance ;
263+ }
264+
265+ private static object ? CreateInstance ( Type type , bool isAutoInitializeModelProperty = false )
266+ {
267+ object ? instance ;
268+ try
269+ {
270+ instance = Activator . CreateInstance ( type ) ;
271+ if ( isAutoInitializeModelProperty )
272+ {
273+ instance . EnsureInitialized ( ) ;
274+ }
275+ }
276+ catch
277+ {
278+ throw ;
279+ }
250280 return instance ;
251281 }
252282
253283 /// <summary>
254284 /// Ensures that all class-type properties of the instance are initialized.
255285 /// </summary>
286+ /// <param name="isAutoInitializeModelProperty">Whether to automatically initialize model properties default value is false.</param>
256287 /// <param name="instance">The instance to initialize properties for.</param>
257- private static void EnsureInitialized ( this object instance )
288+ private static void EnsureInitialized ( this object ? instance , bool isAutoInitializeModelProperty = false )
258289 {
290+ if ( instance is null )
291+ {
292+ return ;
293+ }
294+
259295 // Reflection performance needs to be optimized here
260296 foreach ( var propertyInfo in instance . GetType ( ) . GetProperties ( ) . Where ( p => p . PropertyType . IsClass && p . PropertyType != typeof ( string ) ) )
261297 {
262298 var type = propertyInfo . PropertyType ;
263299 var value = propertyInfo . GetValue ( instance , null ) ;
264300 if ( value is null )
265301 {
266- var pv = CreateInstance ( type ) ;
267- propertyInfo . SetValue ( instance , pv ) ;
302+ var pv = CreateInstance ( type , isAutoInitializeModelProperty ) ;
303+ if ( pv is not null )
304+ {
305+ propertyInfo . SetValue ( instance , pv ) ;
306+ }
268307 }
269308 }
270309 }
271-
272- private static object ? CreateInstance ( Type type )
273- {
274- var instance = Activator . CreateInstance ( type ) ;
275- instance ! . EnsureInitialized ( ) ;
276- return instance ;
277- }
278310}
0 commit comments