22using System . Collections . Generic ;
33using System . Reflection ;
44using System . Reflection . Emit ;
5+ using System . Runtime . InteropServices ;
56
67namespace mojoPortal . Web . Components ;
78
@@ -65,8 +66,7 @@ public DynamicTypeGenerator AddProperties(Dictionary<string, Type> properties)
6566
6667 public Type CreateType ( )
6768 {
68- // Return from constructor
69- //_ctorIL.Emit(OpCodes.Ret);
69+ _ctorIL . Emit ( OpCodes . Ret ) ; // Return from constructor
7070 return _typeBuilder . CreateType ( ) ;
7171 }
7272
@@ -93,9 +93,29 @@ private void CreateClass(string name)
9393 }
9494
9595
96+ //private void CreateConstructor()
97+ //{
98+ // _typeBuilder.DefineDefaultConstructor(MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName);
99+ //}
100+
101+
96102 private void CreateConstructor ( )
97103 {
98- _typeBuilder . DefineDefaultConstructor ( MethodAttributes . Public | MethodAttributes . SpecialName | MethodAttributes . RTSpecialName ) ;
104+ // Define a public, parameterless constructor
105+ var ctorBuilder = _typeBuilder . DefineConstructor (
106+ MethodAttributes . Public | MethodAttributes . SpecialName | MethodAttributes . RTSpecialName ,
107+ CallingConventions . Standard ,
108+ Type . EmptyTypes
109+ ) ;
110+
111+ _ctorIL = ctorBuilder . GetILGenerator ( ) ;
112+
113+ // 1. Call the base class (System.Object) constructor
114+ var objectCtor = typeof ( object ) . GetConstructor ( Type . EmptyTypes ) ;
115+ _ctorIL . Emit ( OpCodes . Ldarg_0 ) ; // Load 'this'
116+ _ctorIL . Emit ( OpCodes . Call , objectCtor ) ; // Call object..ctor()
117+
118+
99119 }
100120
101121
@@ -156,6 +176,15 @@ private void CreateProperty(string propertyName, Type type)
156176
157177 propertyBuilder . SetGetMethod ( getPropertyMethodBuilder ) ;
158178 propertyBuilder . SetSetMethod ( setPropertyMethodBuilder ) ;
179+
180+ if ( type . IsGenericType && type . GetGenericTypeDefinition ( ) == typeof ( List < > ) )
181+ {
182+ // Initialize property
183+ var listStringCtor = type . GetConstructor ( Type . EmptyTypes ) ;
184+ _ctorIL . Emit ( OpCodes . Ldarg_0 ) ; // Load 'this' (for the stfld operation later)
185+ _ctorIL . Emit ( OpCodes . Newobj , listStringCtor ) ; // Create new object instance
186+ _ctorIL . Emit ( OpCodes . Stfld , fieldBuilder ) ; // Assign instance to backing field
187+ }
159188 }
160189
161190
0 commit comments