Exemplo n.º 1
0
        private static Type Type(
            string name, Type[] interfaces, MemberDefinition[] memberDefinitions,
            TypeAttributes typeAttributes, Type baseType = null)
        {
            if (name == null) throw new ArgumentNullException("name");
            if (interfaces == null) throw new ArgumentNullException("interfaces");
            if (memberDefinitions == null) throw new ArgumentNullException("memberDefinitions");

            var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(
                new AssemblyName(name), AssemblyBuilderAccess.Run);

            var moduleBuilder = assemblyBuilder.DefineDynamicModule("MainModule");

            var typeBuilder = moduleBuilder.DefineType(name, typeAttributes, baseType, interfaces);

            var fields = new List<FieldBuilder>();

            foreach (var definition in memberDefinitions.OrderBy(d => d is ConstructorDefinition))
            {
                definition.EmitTo(typeBuilder, fields);
            }

            if (baseType != typeof(ValueType)
                && !memberDefinitions.Any(d => d is ConstructorDefinition))
            {
                Define.Constructor().EmitTo(typeBuilder, fields);
            }

            return typeBuilder.CreateType();
        }
Exemplo n.º 2
0
        private static MemberDefinition NestedType(string name, Type[] interfaces,
            MemberDefinition[] memberDefinitions, TypeAttributes typeAttributes,
            Visibility visibility, Type baseType = null)
        {
            if (name == null) throw new ArgumentNullException("name");
            if (interfaces == null) throw new ArgumentNullException("interfaces");
            if (memberDefinitions == null) throw new ArgumentNullException("memberDefinitions");

            typeAttributes |= GetNestedVisibility(visibility);

            return new MemberDefinition((tb, fields) =>
            {
                var nestedTypeBuilder = tb.DefineNestedType(name, typeAttributes, baseType, interfaces);

                var nestedFields = new List<FieldBuilder>();

                foreach (var definition in memberDefinitions.OrderBy(d => d is ConstructorDefinition))
                {
                    definition.EmitTo(nestedTypeBuilder, nestedFields);
                }

                if (baseType != typeof(ValueType)
                    && !memberDefinitions.Any(d => d is ConstructorDefinition))
                {
                    // ReSharper disable once RedundantNameQualifier
                    Define.Constructor().EmitTo(nestedTypeBuilder, nestedFields);
                }

                nestedTypeBuilder.CreateType();
            });
        }