@@ -242,37 +242,53 @@ 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 ? CreateInstance < TItem > ( bool isAutoInitializeModelProperty = false )
247248 {
248249 var instance = Activator . CreateInstance < TItem > ( ) ;
249- instance ! . EnsureInitialized ( ) ;
250+ if ( isAutoInitializeModelProperty )
251+ {
252+ instance . EnsureInitialized ( isAutoInitializeModelProperty ) ;
253+ }
254+ return instance ;
255+ }
256+
257+ private static object ? CreateInstance ( Type type , bool isAutoInitializeModelProperty = false )
258+ {
259+ var instance = Activator . CreateInstance ( type ) ;
260+ if ( isAutoInitializeModelProperty )
261+ {
262+ instance . EnsureInitialized ( ) ;
263+ }
250264 return instance ;
251265 }
252266
253267 /// <summary>
254268 /// Ensures that all class-type properties of the instance are initialized.
255269 /// </summary>
270+ /// <param name="isAutoInitializeModelProperty">Whether to automatically initialize model properties default value is false.</param>
256271 /// <param name="instance">The instance to initialize properties for.</param>
257- private static void EnsureInitialized ( this object instance )
272+ private static void EnsureInitialized ( this object ? instance , bool isAutoInitializeModelProperty = false )
258273 {
274+ if ( instance is null )
275+ {
276+ return ;
277+ }
278+
259279 // Reflection performance needs to be optimized here
260280 foreach ( var propertyInfo in instance . GetType ( ) . GetProperties ( ) . Where ( p => p . PropertyType . IsClass && p . PropertyType != typeof ( string ) ) )
261281 {
262282 var type = propertyInfo . PropertyType ;
263283 var value = propertyInfo . GetValue ( instance , null ) ;
264284 if ( value is null )
265285 {
266- var pv = CreateInstance ( type ) ;
267- propertyInfo . SetValue ( instance , pv ) ;
286+ var pv = CreateInstance ( type , isAutoInitializeModelProperty ) ;
287+ if ( pv is not null )
288+ {
289+ propertyInfo . SetValue ( instance , pv ) ;
290+ }
268291 }
269292 }
270293 }
271-
272- private static object ? CreateInstance ( Type type )
273- {
274- var instance = Activator . CreateInstance ( type ) ;
275- instance ! . EnsureInitialized ( ) ;
276- return instance ;
277- }
278294}
0 commit comments