@@ -242,37 +242,53 @@ internal static void Clone<TModel>(this TModel source, TModel item)
242
242
/// Creates an instance of a type and ensures all class-type properties are initialized.
243
243
/// </summary>
244
244
/// <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>
245
246
/// <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 )
247
248
{
248
249
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
+ }
250
264
return instance ;
251
265
}
252
266
253
267
/// <summary>
254
268
/// Ensures that all class-type properties of the instance are initialized.
255
269
/// </summary>
270
+ /// <param name="isAutoInitializeModelProperty">Whether to automatically initialize model properties default value is false.</param>
256
271
/// <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 )
258
273
{
274
+ if ( instance is null )
275
+ {
276
+ return ;
277
+ }
278
+
259
279
// Reflection performance needs to be optimized here
260
280
foreach ( var propertyInfo in instance . GetType ( ) . GetProperties ( ) . Where ( p => p . PropertyType . IsClass && p . PropertyType != typeof ( string ) ) )
261
281
{
262
282
var type = propertyInfo . PropertyType ;
263
283
var value = propertyInfo . GetValue ( instance , null ) ;
264
284
if ( value is null )
265
285
{
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
+ }
268
291
}
269
292
}
270
293
}
271
-
272
- private static object ? CreateInstance ( Type type )
273
- {
274
- var instance = Activator . CreateInstance ( type ) ;
275
- instance ! . EnsureInitialized ( ) ;
276
- return instance ;
277
- }
278
294
}
0 commit comments