Exemple #1
0
        private static Type InternalCreateType(IDataReader reader, IEnumerable <Type> implInterfaceTypes)
        {
            var guid        = Guid.NewGuid().ToString("N");
            var typeBuilder = new DynamicAssemblyBuilder("_Dynamic_" + guid).DefineType("$<>" + guid);

            foreach (var type in implInterfaceTypes)
            {
                typeBuilder.ImplementInterface(type);
            }

            var length = reader.FieldCount;
            var fields = new DynamicFieldBuilder[length];

            for (var i = 0; i < length; i++)
            {
                var name = GetFieldName(reader.GetName(i));
                var type = reader.GetFieldType(i);

                var fieldBuilder = typeBuilder.DefineField("<>__" + name, type);
                typeBuilder.DefineProperty(name, type).DefineGetSetMethods(fieldBuilder);
                fields[i] = fieldBuilder;
            }

            var constructorBuilder = typeBuilder.DefineConstructor(new[] { typeof(IDataReader), typeof(IRecordWrapper) }, ilCoding: bc =>
                                                                   bc.Emitter
                                                                   .For(0, length, (e, i) =>
                                                                        e.ldarg_0
                                                                        .ldarg_2
                                                                        .ldarg_1
                                                                        .ldc_i4(i)
                                                                        .callvirt(RecordWrapHelper.GetGetValueMethod(reader.GetFieldType(i)))
                                                                        .stfld(fields[i].FieldBuilder))
                                                                   .ret());

            constructorBuilder.DefineParameter("reader");
            constructorBuilder.DefineParameter("wrapper");

            return(typeBuilder.CreateType());
        }