Beispiel #1
0
        private Type CreateTypeInternal(DynamicTypeDescriptor typeDescriptor)
        {
            var tb = GetTypeBuilder(typeDescriptor.Name, typeDescriptor.BaseType);

            foreach (var iface in typeDescriptor.Interfaces)
            {
                tb.AddInterfaceImplementation(iface);
            }

            var propertyBuilders = typeDescriptor.Properties.Select(x => (x, CreateProperty(tb, x, typeDescriptor.Interfaces, out var fieldBuilder), fieldBuilder)).ToList();
            var fieldBuilders    = typeDescriptor.Fields.Select(x => (x, CreateField(tb, x))).ToList();

            var defaultConstructor = tb.DefineDefaultConstructor(MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName);

            CreateConstructor(tb,
                              propertyBuilders,
                              fieldBuilders,
                              defaultConstructor);

            if (typeDescriptor.AttributeBuilders != null)
            {
                foreach (var a in typeDescriptor.AttributeBuilders)
                {
                    tb.SetCustomAttribute(a);
                }
            }

            return(tb.CreateType());
        }
Beispiel #2
0
        public Type CreateType(DynamicTypeDescriptor descriptor)
        {
            lock (olock)
            {
                if (descriptor.Name.IsNullOrEmpty())
                {
                    descriptor.Name = "DynamicType_" + NextIncrement();
                }

                if (!typeCache.TryGetValue(descriptor.Name, out Type type))
                {
                    type = CreateTypeInternal(descriptor);
                    typeCache.Add(descriptor.Name, type);
                }

                return(type);
            }
        }
 public DynamicTypeDescriptorBuilder(string name = null, IEnumerable <DynamicTypeProperty> properties = null, IEnumerable <DynamicTypeField> fields = null, IEnumerable <Type> interfaces = null, Type baseType = null)
 {
     dynamicTypeDescriptor = new DynamicTypeDescriptor(name, properties, fields, interfaces, baseType);
 }