Due to some special requirements and scenarios of the underlying architecture of recent projects, it is required to dynamically build an object,
The attribute names, classes, and types are dynamically passed in.
If you don't talk nonsense much, go directly to my original code:
[] namelist = [] { , Dictionary<, Type> dic = Dictionary<, Type> dic.Add(, ( dic.Add(, ( strDynamicModuleName = strDynamicClassName = AppDomain currentDomain = AssemblyName assemblyName = assemblyName.Name = AssemblyBuilder assemblyBuilder = ModuleBuilder moduleBuilder = TypeBuilder typeBuilder = Type[] methodArgs = { ( ConstructorBuilder constructorBuiler = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, Type[] { (), ( index = ILGenerator ilg = ( item FieldBuilder fieldBuilder = typeBuilder.DefineField(dic[item].Name + + index++ ilg.Emit(OpCodes.Ldarg_0); ilg.Emit(OpCodes.Ldarg, index); ilg.Emit(OpCodes.Stfld, fieldBuilder); PropertyBuilder propertyBuilder = typeBuilder.DefineProperty(item, PropertyAttributes.None, dic[item], MethodBuilder methodBuilder = typeBuilder.DefineMethod( + item, MethodAttributes.Public, dic[item], ILGenerator ilGenerator = ilGenerator.Emit(OpCodes.Ldfld, fieldBuilder); propertyBuilder.SetGetMethod(methodBuilder); methodBuilder = typeBuilder.DefineMethod( + (), ilGenerator = propertyBuilder.SetSetMethod(methodBuilder); Type type = objReturn = Activator.CreateInstance(type, , }
Specifically:
Ldarg.0 is not translated here.
NOTE: ldarg.0 holds the "this" reference-ldarg.1, ldarg.2, and ldarg.3
Hold the actual passed parameters. ldarg.0 is used by instance methods
To hold a reference to the current calling object instance. Static methods
Do not use arg.0, since they are not instantiated and hence no reference
Is needed to distinguish them.
The test code is as follows:
Type myDynamicType = Console.WriteLine( Console.WriteLine( Console.WriteLine( Console.WriteLine( Console.WriteLine( (MemberInfo member Console.WriteLine( Console.WriteLine( Type[] aPtypes = Type[] { (), ( [] aPargs = [] { , ConstructorInfo myDTctor = Console.WriteLine( Console.WriteLine( amyclass = Console.WriteLine( Console.WriteLine( (MethodInfo method (method.Name.StartsWith( v = method.Invoke(amyclass, Console.WriteLine(method.Name + + Console.WriteLine( (PropertyInfo property Console.WriteLine(property.Name + + }
The running result is as follows: