Пример #1
0
        static Column()
        {
            Type type = typeof(valueType);

            if (type.IsEnum || !type.IsValueType)
            {
                AutoCSer.LogHelper.Error(type.fullName() + " 非值类型,不能用作数据列", LogLevel.Error | LogLevel.AutoCSer);
                return;
            }
            attribute = TypeAttribute.GetAttribute <ColumnAttribute>(type, true) ?? ColumnAttribute.Default;
            foreach (MethodInfo method in type.GetMethods(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic))
            {
#if NOJIT
                if (typeof(ICustom).IsAssignableFrom(method.ReturnType)
#else
                if (typeof(ICustom <valueType>).IsAssignableFrom(method.ReturnType)
#endif
                    && method.GetParameters().Length == 0 && method.IsDefined(typeof(ColumnAttribute), false))
                {
                    object customValue = method.Invoke(null, null);
                    if (customValue != null)
                    {
#if NOJIT
                        custom = (ICustom)customValue;
#else
                        custom = (ICustom <valueType>)customValue;
#endif
                        return;
                    }
                }
            }
            Fields      = Field.Get(MemberIndexGroup <valueType> .GetFields(attribute.MemberFilters), true).ToArray();
            dataColumns = new AutoCSer.Threading.LockDictionary <HashString, KeyValue <string, Type>[]>();
            AutoCSer.Memory.Common.AddClearCache(dataColumns.Clear, typeof(Column <valueType>), 60 * 60);
        }
Пример #2
0
 /// <summary>
 /// 根据类型获取成员信息集合
 /// </summary>
 /// <param name="type">类型</param>
 /// <returns>成员信息集合</returns>
 private static MemberIndex[] getStaticMembers(Type type)
 {
     MemberIndex[] members;
     if (!staticMemberCache.TryGetValue(type, out members))
     {
         MemberIndexGroup group = StaticMemberIndexGroup.Get(type);
         staticMemberCache[type] = members =
             ArrayExtension.concat(group.PublicFields.getArray(value => new MemberIndex(value)),
                                   group.NonPublicFields.getArray(value => new MemberIndex(value)),
                                   group.PublicProperties.getArray(value => new MemberIndex(value)),
                                   group.NonPublicProperties.getArray(value => new MemberIndex(value)));
     }
     return(members);
 }
Пример #3
0
        /// <summary>
        /// 根据类型获取成员索引分组
        /// </summary>
        /// <param name="type">对象类型</param>
        /// <returns>成员索引分组</returns>
        private static MemberIndexGroup getStatic(Type type)
        {
            MemberIndexGroup value;

            Monitor.Enter(cacheLock);
            try
            {
                if (!cache.TryGetValue(type, out value))
                {
                    cache.Add(type, value = new MemberIndexGroup(type, true));
                }
            }
            finally { Monitor.Exit(cacheLock); }
            return(value);
        }
Пример #4
0
        static Model()
        {
            Type type = typeof(valueType);

            attribute   = TypeAttribute.GetAttribute <ModelAttribute>(type, true) ?? ModelAttribute.Default;
            Fields      = Field.Get(MemberIndexGroup <valueType> .GetFields(attribute.MemberFilters), false).ToArray();
            Identity    = Field.GetIdentity(Fields);
            PrimaryKeys = Field.GetPrimaryKeys(Fields).ToArray();
            MemberMap   = new MemberMap <valueType>();
            foreach (Field field in Fields)
            {
                MemberMap.SetMember(field.MemberMapIndex);
            }
            if (Identity != null)
            {
                IdentitySqlName = Identity.SqlFieldName;
#if NOJIT
                new identity(Identity.Field).Get(out GetIdentity, out SetIdentity);
                Action <valueType, int> setter32;
                new identity32(Identity.Field).Get(out GetIdentity32, out setter32);
#else
                DynamicMethod dynamicMethod = new DynamicMethod("GetSqlIdentity", typeof(long), new Type[] { type }, type, true);
                ILGenerator   generator     = dynamicMethod.GetILGenerator();
                generator.Emit(OpCodes.Ldarg_0);
                generator.Emit(OpCodes.Ldfld, Identity.FieldInfo);
                if (Identity.FieldInfo.FieldType != typeof(long) && Identity.FieldInfo.FieldType != typeof(ulong))
                {
                    generator.Emit(OpCodes.Conv_I8);
                }
                generator.Emit(OpCodes.Ret);
                GetIdentity = (Func <valueType, long>)dynamicMethod.CreateDelegate(typeof(Func <valueType, long>));

                dynamicMethod = new DynamicMethod("SetSqlIdentity", null, new Type[] { type, typeof(long) }, type, true);
                generator     = dynamicMethod.GetILGenerator();
                generator.Emit(OpCodes.Ldarg_0);
                generator.Emit(OpCodes.Ldarg_1);
                if (Identity.FieldInfo.FieldType != typeof(long) && Identity.FieldInfo.FieldType != typeof(ulong))
                {
                    generator.Emit(OpCodes.Conv_I4);
                }
                generator.Emit(OpCodes.Stfld, Identity.FieldInfo);
                generator.Emit(OpCodes.Ret);
                SetIdentity = (Action <valueType, long>)dynamicMethod.CreateDelegate(typeof(Action <valueType, long>));

                GetIdentity32 = getIdentityGetter32("GetSqlIdentity32", Identity.FieldInfo);
#endif
            }
        }
 /// <summary>
 /// 安装下一个类型
 /// </summary>
 protected unsafe override void nextCreate()
 {
     if (Type.Type.IsClass && !Type.Type.IsAbstract)
     {
         LeftArray <TcpMethod> methodArray = new LeftArray <TcpMethod>(Metadata.MethodIndex.GetMethods <AutoCSer.Net.TcpStreamServer.MethodAttribute>(Type, Attribute.MemberFilters, false, Attribute.IsAttribute, Attribute.IsBaseTypeAttribute)
                                                                       .getFind(value => !value.Method.IsGenericMethod)
                                                                       .getArray(value => new TcpMethod
         {
             Method           = value,
             MethodType       = Type,
             ServiceAttribute = Attribute
         }));
         foreach (MemberIndexInfo member in MemberIndexGroup.Get <AutoCSer.Net.TcpStreamServer.MethodAttribute>(Type, Attribute.MemberFilters, false, Attribute.IsAttribute, Attribute.IsBaseTypeAttribute))
         {
             if (member.IsField)
             {
                 FieldInfo field     = (FieldInfo)member.Member;
                 TcpMethod getMethod = new TcpMethod
                 {
                     Method           = new Metadata.MethodIndex(field, true),
                     MemberIndex      = member,
                     MethodType       = Type,
                     ServiceAttribute = Attribute
                 };
                 if (!getMethod.Attribute.IsOnlyGetMember)
                 {
                     getMethod.SetMethod = new TcpMethod {
                         Method = new MethodIndex(field, false), MemberIndex = member, MethodType = Type, ServiceAttribute = Attribute
                     };
                 }
                 methodArray.Add(getMethod);
                 if (getMethod.SetMethod != null)
                 {
                     methodArray.Add(getMethod.SetMethod);
                 }
             }
             else if (member.CanGet)
             {
                 PropertyInfo property  = (PropertyInfo)member.Member;
                 TcpMethod    getMethod = new TcpMethod
                 {
                     Method           = new MethodIndex(property, true),
                     MemberIndex      = member,
                     MethodType       = Type,
                     ServiceAttribute = Attribute
                 };
                 if (member.CanSet && !getMethod.Attribute.IsOnlyGetMember)
                 {
                     getMethod.SetMethod = new TcpMethod {
                         Method = new MethodIndex(property, false), MemberIndex = member, MethodType = Type, ServiceAttribute = Attribute
                     };
                 }
                 methodArray.Add(getMethod);
                 if (getMethod.SetMethod != null)
                 {
                     methodArray.Add(getMethod.SetMethod);
                 }
             }
         }
         MethodIndexs = methodArray.ToArray();
         MethodIndexs = TcpMethod.CheckIdentity(MethodIndexs, getRememberIdentityName(Attribute.GenericType ?? Type), method => method.Method.MethodKeyFullName);
         if (MethodIndexs == null)
         {
             return;
         }
         int methodIndex = 0;
         IsVerifyMethod = false;
         ParameterBuilder parameterBuilder = new ParameterBuilder {
             IsSimpleSerialize = Attribute.IsSimpleSerialize
         };
         foreach (TcpMethod method in MethodIndexs)
         {
             method.MethodIndex = methodIndex++;
             if (!method.IsNullMethod)
             {
                 if (IsVerifyMethod)
                 {
                     method.Attribute.IsVerifyMethod = false;
                 }
                 else if (method.IsVerifyMethod)
                 {
                     IsVerifyMethod = true;
                 }
                 parameterBuilder.Add(method);
             }
         }
         ParameterTypes = parameterBuilder.Get();
         //TcpMethod[] methodIndexs = MethodIndexs.getFindArray(value => !value.IsNullMethod);
         if (ServiceAttribute.IsSegmentation)
         {
             IsClientCode        = false;
             create(IsServerCode = true);
             CSharpTypeDefinition definition = new CSharpTypeDefinition(Type, IsClientCode = true, false, Type.Type.Namespace + ".TcpStreamClient");
             _code_.Length = 0;
             _code_.Add(definition.Start);
             create(IsServerCode = false);
             _code_.Add(definition.End);
             string fileName   = AutoParameter.ProjectPath + "{" + AutoParameter.DefaultNamespace + "}.TcpInternalStreamServer." + ServerName + ".Client.cs";
             string clientCode = Coder.WarningCode + _code_.ToString() + Coder.FileEndCode;
             if (Coder.WriteFile(fileName, clientCode))
             {
                 if (ServiceAttribute.ClientSegmentationCopyPath != null)
                 {
                     string copyFileName = ServiceAttribute.ClientSegmentationCopyPath + "{" + AutoParameter.DefaultNamespace + "}.TcpInternalStreamServer." + ServerName + ".Client.cs";
                     if (Coder.WriteFile(copyFileName, clientCode))
                     {
                         Messages.Message(copyFileName + " 被修改");
                     }
                 }
                 Messages.Message(fileName + " 被修改");
             }
         }
         else
         {
             create(IsServerCode = IsClientCode = true);
         }
     }
 }
Пример #6
0
        static TypeSerializer()
        {
            Type type = typeof(valueType);
            int  memberCountVerify;

            BinarySerialize.Fields <BinarySerialize.FieldSize> fields = BinarySerialize.SerializeMethodCache.GetFields(MemberIndexGroup <valueType> .GetFields(MemberFilters.PublicInstanceField), false, out memberCountVerify);
#if NOJIT
            fixedFillSize   = -fields.FixedSize & 3;
            fixedSize       = (fields.FixedSize + fields.FieldArray.Length * sizeof(int) + 3) & (int.MaxValue - 3);
            fixedSerializer = new FieldFerializer(ref fields.FixedFields).Serialize;
            if (fields.FieldArray.Length != 0)
            {
                serializer = new FieldFerializer(ref fields.FieldArray).Serialize;
            }
#else
            SerializeDynamicMethod dynamicMethod = new SerializeDynamicMethod(type, (fields.FixedSize + fields.FieldArray.Length * sizeof(int) + 3) & (int.MaxValue - 3));
            foreach (BinarySerialize.FieldSize member in fields.FixedFields)
            {
                dynamicMethod.Push(member);
            }
            dynamicMethod.FixedFill(-fields.FixedSize & 3);
            foreach (BinarySerialize.FieldSize member in fields.FieldArray)
            {
                dynamicMethod.Push(member);
            }
            Serializer = (SimpleSerializer)dynamicMethod.Create <SimpleSerializer>();
#endif
        }
Пример #7
0
 /// <summary>
 /// 获取字段成员集合
 /// </summary>
 /// <typeparam name="valueType"></typeparam>
 /// <param name="memberFilter"></param>
 /// <returns>字段成员集合</returns>
 internal static KeyValue <FieldInfo, int>[] GetFieldIndexs <valueType>(MemberFilters memberFilter)
 {
     return(MemberIndexGroup <valueType> .GetFields(memberFilter)
            .getArray(value => new KeyValue <FieldInfo, int>(value.Member, value.MemberIndex)));
 }
Пример #8
0
        static TypeDeSerializer()
        {
            Type       type       = typeof(T);
            MethodInfo methodInfo = XmlDeSerializer.GetDeSerializeMethod(type);

            if (methodInfo != null)
            {
                DefaultDeSerializer = (XmlDeSerializer.DeSerializeDelegate <T>)Delegate.CreateDelegate(typeof(XmlDeSerializer.DeSerializeDelegate <T>), methodInfo);
                return;
            }
            if (type.IsArray)
            {
                if (type.GetArrayRank() == 1)
                {
                    DefaultDeSerializer = (XmlDeSerializer.DeSerializeDelegate <T>)GenericType.Get(type.GetElementType()).XmlDeSerializeArrayMethod;
                }
                else
                {
                    DefaultDeSerializer = notSupport;
                }
                return;
            }
            if (type.IsEnum)
            {
                if (type.IsDefined(typeof(FlagsAttribute), false))
                {
                    DefaultDeSerializer = (XmlDeSerializer.DeSerializeDelegate <T>)EnumGenericType.Get(type).XmlDeSerializeEnumFlagsDelegate;
                }
                else
                {
                    DefaultDeSerializer = (XmlDeSerializer.DeSerializeDelegate <T>)EnumGenericType.Get(type).XmlDeSerializeEnumDelegate;
                }
                return;
            }
            if (type.IsInterface || type.IsPointer || typeof(Delegate).IsAssignableFrom(type))
            {
                DefaultDeSerializer = notSupport;
                return;
            }
            if (type.IsGenericType)
            {
                Type genericType = type.GetGenericTypeDefinition();
                if (genericType == typeof(Nullable <>))
                {
                    Type[] parameterTypes = type.GetGenericArguments();
                    DefaultDeSerializer = (XmlDeSerializer.DeSerializeDelegate <T>)(parameterTypes[0].IsEnum ? StructGenericType.Get(parameterTypes[0]).XmlDeSerializeNullableEnumMethod : StructGenericType.Get(parameterTypes[0]).XmlDeSerializeNullableMethod);
                    return;
                }
                if (genericType == typeof(KeyValuePair <,>))
                {
                    DefaultDeSerializer = (XmlDeSerializer.DeSerializeDelegate <T>)GenericType2.Get(type.GetGenericArguments()).XmlDeSerializeKeyValuePairMethod;
                    isValueType         = true;
                    return;
                }
            }
            if ((methodInfo = DeSerializeMethodCache.GetCustom(type)) != null)
            {
                if (type.IsValueType)
                {
#if NOJIT
                    DefaultDeSerializer = new CustomDeSerializer(methodInfo).DeSerialize;
#else
                    DynamicMethod dynamicMethod = new DynamicMethod("CustomXmlDeSerializer", null, new Type[] { typeof(XmlDeSerializer), type.MakeByRefType() }, type, true);
                    ILGenerator   generator     = dynamicMethod.GetILGenerator();
                    generator.Emit(OpCodes.Ldarg_1);
                    generator.Emit(OpCodes.Ldarg_0);
                    generator.call(methodInfo);
                    generator.Emit(OpCodes.Ret);
                    DefaultDeSerializer = (XmlDeSerializer.DeSerializeDelegate <T>)dynamicMethod.CreateDelegate(typeof(XmlDeSerializer.DeSerializeDelegate <T>));
#endif
                }
                else
                {
                    DefaultDeSerializer = (XmlDeSerializer.DeSerializeDelegate <T>)Delegate.CreateDelegate(typeof(XmlDeSerializer.DeSerializeDelegate <T>), methodInfo);
                }
            }
            else
            {
                Type attributeType;
                attribute = type.customAttribute <XmlSerializeAttribute>(out attributeType) ?? XmlSerializer.AllMemberAttribute;
                if ((methodInfo = DeSerializeMethodCache.GetIEnumerableConstructor(type)) != null)
                {
                    DefaultDeSerializer = (XmlDeSerializer.DeSerializeDelegate <T>)Delegate.CreateDelegate(typeof(XmlDeSerializer.DeSerializeDelegate <T>), methodInfo);
                }
                else
                {
                    if (type.IsValueType)
                    {
                        isValueType = true;
                    }
                    else if (attribute != XmlSerializer.AllMemberAttribute && attributeType != type)
                    {
                        for (Type baseType = type.BaseType; baseType != typeof(object); baseType = baseType.BaseType)
                        {
                            XmlSerializeAttribute baseAttribute = baseType.customAttribute <XmlSerializeAttribute>();
                            if (baseAttribute != null)
                            {
                                if (baseAttribute.IsBaseType)
                                {
                                    methodInfo          = DeSerializeMethodCache.BaseDeSerializeMethod.MakeGenericMethod(baseType, type);
                                    DefaultDeSerializer = (XmlDeSerializer.DeSerializeDelegate <T>)Delegate.CreateDelegate(typeof(XmlDeSerializer.DeSerializeDelegate <T>), methodInfo);
                                    return;
                                }
                                break;
                            }
                        }
                    }
                    if (type.IsValueType)
                    {
                        foreach (AutoCSer.Metadata.AttributeMethod attributeMethod in AutoCSer.Metadata.AttributeMethod.GetStatic(type))
                        {
                            if (attributeMethod.Method.ReturnType == typeof(bool))
                            {
                                ParameterInfo[] parameters = attributeMethod.Method.GetParameters();
                                if (parameters.Length == 2 && parameters[0].ParameterType == typeof(XmlDeSerializer) && parameters[1].ParameterType == Emit.Pub.PointerSizeRefType)
                                {
                                    if (attributeMethod.GetAttribute <UnknownNameAttribute>() != null)
                                    {
#if NOJIT
                                        onUnknownName = new UnknownDeSerializer(methodInfo).DeSerialize;
#else
                                        DynamicMethod dynamicMethod = new DynamicMethod("XmlUnknownDeSerialize", null, new Type[] { typeof(XmlDeSerializer), type.MakeByRefType(), Emit.Pub.PointerSizeRefType }, type, true);
                                        ILGenerator   generator     = dynamicMethod.GetILGenerator();
                                        generator.Emit(OpCodes.Ldarg_1);
                                        generator.Emit(OpCodes.Ldarg_0);
                                        generator.Emit(OpCodes.Ldarg_2);
                                        generator.call(methodInfo);
                                        generator.Emit(OpCodes.Ret);
                                        onUnknownName = (UnknownDeSerialize)dynamicMethod.CreateDelegate(typeof(UnknownDeSerialize));
#endif
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        Type refType = type.MakeByRefType();
                        foreach (AutoCSer.Metadata.AttributeMethod attributeMethod in AutoCSer.Metadata.AttributeMethod.GetStatic(type))
                        {
                            if (attributeMethod.Method.ReturnType == typeof(bool))
                            {
                                ParameterInfo[] parameters = attributeMethod.Method.GetParameters();
                                if (parameters.Length == 3 && parameters[0].ParameterType == typeof(XmlDeSerializer) && parameters[1].ParameterType == refType && parameters[2].ParameterType == Emit.Pub.PointerSizeRefType)
                                {
                                    if (attributeMethod.GetAttribute <UnknownNameAttribute>() != null)
                                    {
                                        onUnknownName = (UnknownDeSerialize)Delegate.CreateDelegate(typeof(UnknownDeSerialize), attributeMethod.Method);
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    FieldIndex defaultMember = null;
                    LeftArray <KeyValue <FieldIndex, XmlSerializeMemberAttribute> > fields = SerializeMethodCache.GetFields(MemberIndexGroup <T> .GetFields(attribute.MemberFilters), attribute);
                    LeftArray <PropertyMethod> properties = DeSerializeMethodCache.GetProperties(MemberIndexGroup <T> .GetProperties(attribute.MemberFilters), attribute);
                    bool isBox = false;
                    if (type.IsValueType && fields.Length + properties.Length == 1)
                    {
                        BoxSerializeAttribute boxSerialize = AutoCSer.Metadata.TypeAttribute.GetAttribute <BoxSerializeAttribute>(type);
                        if (boxSerialize != null && boxSerialize.IsXml)
                        {
                            isBox         = true;
                            defaultMember = null;
                        }
                    }
                    TryDeSerializeFilter[] deSerializers = new TryDeSerializeFilter[fields.Length + properties.Length + (defaultMember == null ? 0 : 1)];
                    //memberMap.type memberMapType = memberMap<valueType>.TypeInfo;
                    string[] names = isBox ? null : new string[deSerializers.Length];
                    int      index = 0, nameLength = 0, maxNameLength = 0;
                    foreach (KeyValue <FieldIndex, XmlSerializeMemberAttribute> member in fields)
                    {
                        TryDeSerializeFilter tryDeSerialize = deSerializers[index] = new TryDeSerializeFilter
                        {
#if NOJIT
                            TryDeSerialize = new FieldDeSerializer(member.Key.Member).DeSerializer(),
#else
                            TryDeSerialize = (XmlDeSerializer.DeSerializeDelegate <T>)DeSerializeMethodCache.CreateDynamicMethod(type, member.Key.Member).CreateDelegate(typeof(XmlDeSerializer.DeSerializeDelegate <T>)),
#endif
                            ItemName       = member.Value == null ? null : member.Value.ItemName,
                            MemberMapIndex = member.Key.MemberIndex,
                            //MemberFilter = member.Key.Member.IsPublic ? MemberFilters.PublicInstanceField : MemberFilters.NonPublicInstanceField
                        };
                        if (!isBox)
                        {
                            string name = member.Key.AnonymousName;
                            if (name.Length > maxNameLength)
                            {
                                maxNameLength = name.Length;
                            }
                            nameLength += (names[index++] = name).Length;
                            if (member.Key == defaultMember)
                            {
                                deSerializers[deSerializers.Length - 1] = tryDeSerialize;
                                names[deSerializers.Length - 1]         = string.Empty;
                            }
                        }
                    }
                    foreach (PropertyMethod member in properties)
                    {
                        deSerializers[index] = new TryDeSerializeFilter
                        {
#if NOJIT
                            TryDeSerialize = new PropertyDeSerializer(member.Property.Member).DeSerializer(),
#else
                            TryDeSerialize = (XmlDeSerializer.DeSerializeDelegate <T>)DeSerializeMethodCache.CreateDynamicMethod(type, member.Property.Member, member.Method).CreateDelegate(typeof(XmlDeSerializer.DeSerializeDelegate <T>)),
#endif
                            ItemName       = member.Attribute == null ? null : member.Attribute.ItemName,
                            MemberMapIndex = member.Property.MemberIndex,
                            //MemberFilter = member.Method.IsPublic ? MemberFilters.PublicInstanceProperty : MemberFilters.NonPublicInstanceProperty
                        };
                        if (!isBox)
                        {
                            if (member.Property.Member.Name.Length > maxNameLength)
                            {
                                maxNameLength = member.Property.Member.Name.Length;
                            }
                            nameLength += (names[index++] = member.Property.Member.Name).Length;
                        }
                    }
                    memberDeSerializers = deSerializers;
                    if (isBox)
                    {
                        DefaultDeSerializer = unbox;
                    }
                    else
                    {
                        if (type.Name[0] == '<')
                        {
                            isAnonymousType = true;
                        }
                        if (maxNameLength > (short.MaxValue >> 1) - 2 || nameLength == 0)
                        {
                            memberNames = Unmanaged.NullByte8;
                        }
                        else
                        {
                            memberNames = Unmanaged.GetStaticPointer((nameLength + (names.Length - (defaultMember == null ? 0 : 1)) * 3 + 1) << 1, false);
                            byte *write = memberNames.Byte;
                            foreach (string name in names)
                            {
                                if (name.Length != 0)
                                {
                                    *(short *)write = (short)((name.Length + 2) * sizeof(char));
                                    *(char *)(write + sizeof(short)) = '<';

                                    fixed(char *nameFixed = name) AutoCSer.Extensions.StringExtension.SimpleCopyNotNull(nameFixed, (char *)(write + (sizeof(short) + sizeof(char))), name.Length);

                                    *(char *)(write += (sizeof(short) + sizeof(char)) + (name.Length << 1)) = '>';
                                    write += sizeof(char);
                                }
                            }
                            *(short *)write = 0;
                        }
                        if (type.IsGenericType)
                        {
                            memberSearcher = DeSerializeMethodCache.GetGenericDefinitionMemberSearcher(type, names);
                        }
                        else
                        {
                            memberSearcher = AutoCSer.StateSearcher.CharBuilder.Create(names, true);
                        }
                    }
                }
            }
        }
Пример #9
0
 /// <summary>
 /// 获取数据库成员信息集合
 /// </summary>
 /// <param name="type">数据库绑定类型</param>
 /// <param name="database">数据库配置</param>
 /// <returns>数据库成员信息集合</returns>
 internal static KeyValue <MemberIndexInfo, MemberAttribute>[] GetMemberIndexs <attributeType>(Type type, attributeType database)
     where attributeType : Metadata.MemberFilterAttribute
 {
     return(GetMembers(MemberIndexGroup.Get(type).Find <MemberAttribute>(database)));
 }
Пример #10
0
        static TypeSerializer()
        {
            Type       type = typeof(valueType), attributeType;
            MethodInfo methodInfo = Serializer.GetSerializeMethod(type);

            attribute = type.customAttribute <SerializeAttribute>(out attributeType) ?? Serializer.DefaultAttribute;
            if (methodInfo != null)
            {
                DefaultSerializer = (Action <Serializer, valueType>)Delegate.CreateDelegate(typeof(Action <Serializer, valueType>), methodInfo);
                isValueType       = true;
                IsReferenceMember = false;
                return;
            }
            if (type.IsArray)
            {
                isValueType = true;
                if (type.GetArrayRank() == 1)
                {
                    Type elementType = type.GetElementType();
                    if (!elementType.IsPointer && !typeof(Delegate).IsAssignableFrom(elementType))
                    {
                        if (elementType.IsValueType)
                        {
                            if (elementType.IsEnum)
                            {
                                Type enumType = System.Enum.GetUnderlyingType(elementType);
                                if (enumType == typeof(uint))
                                {
                                    methodInfo = GenericType.Get(elementType).BinarySerializeEnumUIntArrayMethod;                          // SerializeMethodCache.EnumUIntArrayMethod;
                                }
                                else if (enumType == typeof(byte))
                                {
                                    methodInfo = GenericType.Get(elementType).BinarySerializeEnumByteArrayMethod;                               //SerializeMethodCache.EnumByteArrayMethod;
                                }
                                else if (enumType == typeof(ulong))
                                {
                                    methodInfo = GenericType.Get(elementType).BinarySerializeEnumULongArrayMethod;                                //SerializeMethodCache.EnumULongArrayMethod;
                                }
                                else if (enumType == typeof(ushort))
                                {
                                    methodInfo = GenericType.Get(elementType).BinarySerializeEnumUShortArrayMethod;                                 //SerializeMethodCache.EnumUShortArrayMethod;
                                }
                                else if (enumType == typeof(long))
                                {
                                    methodInfo = GenericType.Get(elementType).BinarySerializeEnumLongArrayMethod;                               //SerializeMethodCache.EnumLongArrayMethod;
                                }
                                else if (enumType == typeof(short))
                                {
                                    methodInfo = GenericType.Get(elementType).BinarySerializeEnumShortArrayMethod;                                //SerializeMethodCache.EnumShortArrayMethod;
                                }
                                else if (enumType == typeof(sbyte))
                                {
                                    methodInfo = GenericType.Get(elementType).BinarySerializeEnumSByteArrayMethod;                                //SerializeMethodCache.EnumSByteArrayMethod;
                                }
                                else
                                {
                                    methodInfo = GenericType.Get(elementType).BinarySerializeEnumIntArrayMethod; //SerializeMethodCache.EnumIntArrayMethod;
                                }
                                //methodInfo = methodInfo.MakeGenericMethod(elementType);
                                IsReferenceMember = false;
                            }
                            else if (elementType.IsGenericType && elementType.GetGenericTypeDefinition() == typeof(Nullable <>))
                            {
                                //methodInfo = SerializeMethodCache.NullableArrayMethod.MakeGenericMethod(elementType = elementType.GetGenericArguments()[0]);
                                methodInfo        = StructGenericType.Get(elementType = elementType.GetGenericArguments()[0]).BinarySerializeNullableArrayMethod;
                                IsReferenceMember = SerializeMethodCache.IsReferenceMember(elementType);
                            }
                            else
                            {
                                //methodInfo = SerializeMethodCache.StructArrayMethod.MakeGenericMethod(elementType);
                                methodInfo        = GenericType.Get(elementType).BinarySerializeStructArrayMethod;
                                IsReferenceMember = SerializeMethodCache.IsReferenceMember(elementType);
                            }
                        }
                        else
                        {
                            //methodInfo = SerializeMethodCache.ArrayMethod.MakeGenericMethod(elementType);
                            methodInfo        = ClassGenericType.Get(elementType).BinarySerializeArrayMethod;
                            IsReferenceMember = SerializeMethodCache.IsReferenceMember(elementType);
                        }
                        DefaultSerializer = (Action <Serializer, valueType>)Delegate.CreateDelegate(typeof(Action <Serializer, valueType>), methodInfo);
                        return;
                    }
                }
                DefaultSerializer = toNull;
                IsReferenceMember = false;
                return;
            }
            if (type.IsEnum)
            {
                Type enumType = System.Enum.GetUnderlyingType(type);
                if (enumType == typeof(uint))
                {
                    DefaultSerializer = enumUInt;
                }
                else if (enumType == typeof(byte))
                {
                    DefaultSerializer = enumByte;
                }
                else if (enumType == typeof(ulong))
                {
                    DefaultSerializer = enumULong;
                }
                else if (enumType == typeof(ushort))
                {
                    DefaultSerializer = enumUShort;
                }
                else if (enumType == typeof(long))
                {
                    DefaultSerializer = enumLong;
                }
                else if (enumType == typeof(short))
                {
                    DefaultSerializer = enumShort;
                }
                else if (enumType == typeof(sbyte))
                {
                    DefaultSerializer = enumSByte;
                }
                else
                {
                    DefaultSerializer = enumInt;
                }
                isValueType       = true;
                IsReferenceMember = false;
                return;
            }
            if (type.IsPointer || typeof(Delegate).IsAssignableFrom(type))
            {
                DefaultSerializer = toNull;
                IsReferenceMember = false;
                isValueType       = true;
                return;
            }

            if (type.IsGenericType)
            {
                Type   genericType    = type.GetGenericTypeDefinition();
                Type[] parameterTypes = type.GetGenericArguments();
                if (genericType == typeof(LeftArray <>))
                {
                    //DefaultSerializer = (Action<Serializer, valueType>)Delegate.CreateDelegate(typeof(Action<Serializer, valueType>), SerializeMethodCache.LeftArraySerializeMethod.MakeGenericMethod(parameterTypes));
                    DefaultSerializer = (Action <Serializer, valueType>)Delegate.CreateDelegate(typeof(Action <Serializer, valueType>), GenericType.Get(parameterTypes[0]).BinarySerializeLeftArrayMethod);
                    IsReferenceMember = SerializeMethodCache.IsReferenceMember(parameterTypes[0]);
                    isValueType       = true;
                    return;
                }
#if !Serialize
                if (genericType == typeof(SubArray <>))
                {
                    //DefaultSerializer = (Action<Serializer, valueType>)Delegate.CreateDelegate(typeof(Action<Serializer, valueType>), SerializeMethodCache.SubArraySerializeMethod.MakeGenericMethod(parameterTypes));
                    DefaultSerializer = (Action <Serializer, valueType>)Delegate.CreateDelegate(typeof(Action <Serializer, valueType>), GenericType.Get(parameterTypes[0]).BinarySerializeSubArrayMethod);
                    IsReferenceMember = SerializeMethodCache.IsReferenceMember(parameterTypes[0]);
                    isValueType       = true;
                    return;
                }
#endif
                if (genericType == typeof(Dictionary <,>) || genericType == typeof(SortedDictionary <,>) || genericType == typeof(SortedList <,>))
                {
                    //DefaultSerializer = (Action<Serializer, valueType>)Delegate.CreateDelegate(typeof(Action<Serializer, valueType>), SerializeMethodCache.DictionarySerializeMethod.MakeGenericMethod(type, parameterTypes[0], parameterTypes[1]));
                    DefaultSerializer = (Action <Serializer, valueType>)Delegate.CreateDelegate(typeof(Action <Serializer, valueType>), DictionaryGenericType3.Get(type, parameterTypes[0], parameterTypes[1]).BinarySerializeDictionaryMethod);
                    IsReferenceMember = SerializeMethodCache.IsReferenceMember(parameterTypes[0]) || SerializeMethodCache.IsReferenceMember(parameterTypes[1]);
                    isValueType       = true;
                    return;
                }
                if (genericType == typeof(Nullable <>))
                {
                    //DefaultSerializer = (Action<Serializer, valueType>)Delegate.CreateDelegate(typeof(Action<Serializer, valueType>), SerializeMethodCache.NullableSerializeMethod.MakeGenericMethod(parameterTypes));
                    DefaultSerializer = (Action <Serializer, valueType>)StructGenericType.Get(parameterTypes[0]).BinarySerializeNullableDelegate;
                    IsReferenceMember = SerializeMethodCache.IsReferenceMember(parameterTypes[0]);
                    isValueType       = true;
                    return;
                }
                if (genericType == typeof(KeyValuePair <,>))
                {
                    //DefaultSerializer = (Action<Serializer, valueType>)Delegate.CreateDelegate(typeof(Action<Serializer, valueType>), SerializeMethodCache.KeyValuePairSerializeMethod.MakeGenericMethod(parameterTypes));
                    DefaultSerializer = (Action <Serializer, valueType>)Delegate.CreateDelegate(typeof(Action <Serializer, valueType>), GenericType2.Get(parameterTypes).BinarySerializeKeyValuePairMethod);
                    IsReferenceMember = SerializeMethodCache.IsReferenceMember(parameterTypes[0]) || SerializeMethodCache.IsReferenceMember(parameterTypes[1]);
                    isValueType       = true;
                    return;
                }
            }
            if ((methodInfo = SerializeMethodCache.GetCustom(type, true)) != null)
            {
                if (type.IsValueType)
                {
#if NOJIT
                    DefaultSerializer = new CustomSerializer(methodInfo).Serialize;
#else
                    DynamicMethod dynamicMethod = new DynamicMethod("CustomSerializer", null, new Type[] { typeof(Serializer), type }, type, true);
                    ILGenerator   generator     = dynamicMethod.GetILGenerator();
                    generator.Emit(OpCodes.Ldarga_S, 1);
                    generator.Emit(OpCodes.Ldarg_0);
                    generator.call(methodInfo);
                    generator.Emit(OpCodes.Ret);
                    DefaultSerializer = (Action <Serializer, valueType>)dynamicMethod.CreateDelegate(typeof(Action <Serializer, valueType>));
#endif
                }
                else
                {
                    DefaultSerializer = (Action <Serializer, valueType>)Delegate.CreateDelegate(typeof(Action <Serializer, valueType>), methodInfo);
                }
                IsReferenceMember = attribute.IsReferenceMember;
                isValueType       = true;
                return;
            }
            if (type.IsInterface || type.IsAbstract || Emit.Constructor <valueType> .New == null)
            {
                DefaultSerializer = noConstructor;
                isValueType       = IsReferenceMember = true;
                return;
            }
            ConstructorInfo constructorInfo = null;
            Type            argumentType    = null;
            IsReferenceMember = attribute.IsReferenceMember;
            foreach (Type interfaceType in type.GetInterfaces())
            {
                if (interfaceType.IsGenericType)
                {
                    Type genericType = interfaceType.GetGenericTypeDefinition();
                    if (genericType == typeof(ICollection <>))
                    {
                        Type[] parameterTypes = interfaceType.GetGenericArguments();
                        argumentType      = parameterTypes[0];
                        parameterTypes[0] = argumentType.MakeArrayType();
                        constructorInfo   = type.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, parameterTypes, null);
                        if (constructorInfo != null)
                        {
                            break;
                        }
                        parameterTypes[0] = typeof(IList <>).MakeGenericType(argumentType);
                        constructorInfo   = type.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, parameterTypes, null);
                        if (constructorInfo != null)
                        {
                            break;
                        }
                        parameterTypes[0] = typeof(ICollection <>).MakeGenericType(argumentType);
                        constructorInfo   = type.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, parameterTypes, null);
                        if (constructorInfo != null)
                        {
                            break;
                        }
                        parameterTypes[0] = typeof(IEnumerable <>).MakeGenericType(argumentType);
                        constructorInfo   = type.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, parameterTypes, null);
                        if (constructorInfo != null)
                        {
                            break;
                        }
                    }
                    else if (genericType == typeof(IDictionary <,>))
                    {
                        constructorInfo = type.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { interfaceType }, null);
                        if (constructorInfo != null)
                        {
                            Type[] parameters = interfaceType.GetGenericArguments();
                            //methodInfo = (type.IsValueType ? SerializeMethodCache.StructDictionaryMethod : SerializeMethodCache.ClassDictionaryMethod).MakeGenericMethod(type, parameters[0], parameters[1]);
                            if (type.IsValueType)
                            {
                                methodInfo = DictionaryGenericType3.Get(type, parameters[0], parameters[1]).BinarySerializeStructDictionaryMethod;
                            }
                            else
                            {
                                methodInfo = DictionaryGenericType3.Get(type, parameters[0], parameters[1]).BinarySerializeClassDictionaryMethod;
                            }
                            DefaultSerializer = (Action <Serializer, valueType>)Delegate.CreateDelegate(typeof(Action <Serializer, valueType>), methodInfo);
                            return;
                        }
                    }
                }
            }
            if (constructorInfo != null)
            {
                if (argumentType.IsValueType && argumentType.IsEnum)
                {
                    Type enumType = System.Enum.GetUnderlyingType(argumentType);
                    //if (enumType == typeof(uint)) methodInfo = type.IsValueType ? SerializeMethodCache.StructEnumUIntCollectionMethod : SerializeMethodCache.ClassEnumUIntCollectionMethod;
                    //else if (enumType == typeof(byte)) methodInfo = type.IsValueType ? SerializeMethodCache.StructEnumByteCollectionMethod : SerializeMethodCache.ClassEnumByteCollectionMethod;
                    //else if (enumType == typeof(ulong)) methodInfo = type.IsValueType ? SerializeMethodCache.StructEnumULongCollectionMethod : SerializeMethodCache.ClassEnumULongCollectionMethod;
                    //else if (enumType == typeof(ushort)) methodInfo = type.IsValueType ? SerializeMethodCache.StructEnumUShortCollectionMethod : SerializeMethodCache.ClassEnumUShortCollectionMethod;
                    //else if (enumType == typeof(long)) methodInfo = type.IsValueType ? SerializeMethodCache.StructEnumLongCollectionMethod : SerializeMethodCache.ClassEnumLongCollectionMethod;
                    //else if (enumType == typeof(short)) methodInfo = type.IsValueType ? SerializeMethodCache.StructEnumShortCollectionMethod : SerializeMethodCache.ClassEnumShortCollectionMethod;
                    //else if (enumType == typeof(sbyte)) methodInfo = type.IsValueType ? SerializeMethodCache.StructEnumSByteCollectionMethod : SerializeMethodCache.ClassEnumSByteCollectionMethod;
                    //else methodInfo = type.IsValueType ? SerializeMethodCache.StructEnumIntCollectionMethod : SerializeMethodCache.ClassEnumIntCollectionMethod;
                    //methodInfo = methodInfo.MakeGenericMethod(argumentType, type);
                    if (enumType == typeof(uint))
                    {
                        methodInfo = type.IsValueType ? CollectionGenericType2.Get(type, argumentType).BinarySerializeStructEnumUIntCollectionMethod : CollectionGenericType2.Get(type, argumentType).BinarySerializeClassEnumUIntCollectionMethod;
                    }
                    else if (enumType == typeof(byte))
                    {
                        methodInfo = type.IsValueType ? CollectionGenericType2.Get(type, argumentType).BinarySerializeStructEnumByteCollectionMethod : CollectionGenericType2.Get(type, argumentType).BinarySerializeClassEnumByteCollectionMethod;
                    }
                    else if (enumType == typeof(ulong))
                    {
                        methodInfo = type.IsValueType ? CollectionGenericType2.Get(type, argumentType).BinarySerializeStructEnumULongCollectionMethod : CollectionGenericType2.Get(type, argumentType).BinarySerializeClassEnumULongCollectionMethod;
                    }
                    else if (enumType == typeof(ushort))
                    {
                        methodInfo = type.IsValueType ? CollectionGenericType2.Get(type, argumentType).BinarySerializeStructEnumUShortCollectionMethod : CollectionGenericType2.Get(type, argumentType).BinarySerializeClassEnumUShortCollectionMethod;
                    }
                    else if (enumType == typeof(long))
                    {
                        methodInfo = type.IsValueType ? CollectionGenericType2.Get(type, argumentType).BinarySerializeStructEnumLongCollectionMethod : CollectionGenericType2.Get(type, argumentType).BinarySerializeClassEnumLongCollectionMethod;
                    }
                    else if (enumType == typeof(short))
                    {
                        methodInfo = type.IsValueType ? CollectionGenericType2.Get(type, argumentType).BinarySerializeStructEnumShortCollectionMethod : CollectionGenericType2.Get(type, argumentType).BinarySerializeClassEnumShortCollectionMethod;
                    }
                    else if (enumType == typeof(sbyte))
                    {
                        methodInfo = type.IsValueType ? CollectionGenericType2.Get(type, argumentType).BinarySerializeStructEnumSByteCollectionMethod : CollectionGenericType2.Get(type, argumentType).BinarySerializeClassEnumSByteCollectionMethod;
                    }
                    else
                    {
                        methodInfo = type.IsValueType ? CollectionGenericType2.Get(type, argumentType).BinarySerializeStructEnumIntCollectionMethod : CollectionGenericType2.Get(type, argumentType).BinarySerializeClassEnumIntCollectionMethod;
                    }
                }
                //else methodInfo = (type.IsValueType ? SerializeMethodCache.StructCollectionMethod : SerializeMethodCache.ClassCollectionMethod).MakeGenericMethod(argumentType, type);
                else
                {
                    if (type.IsValueType)
                    {
                        methodInfo = CollectionGenericType2.Get(type, argumentType).BinarySerializeStructCollectionMethod;
                    }
                    else
                    {
                        methodInfo = CollectionGenericType2.Get(type, argumentType).BinarySerializeClassCollectionMethod;
                    }
                }
                DefaultSerializer = (Action <Serializer, valueType>)Delegate.CreateDelegate(typeof(Action <Serializer, valueType>), methodInfo);
                return;
            }
            if (type.IsValueType)
            {
                isValueType = true;
            }
            else if (attribute != Serializer.DefaultAttribute && attributeType != type)
            {
                for (Type baseType = type.BaseType; baseType != typeof(object); baseType = baseType.BaseType)
                {
                    SerializeAttribute baseAttribute = baseType.customAttribute <SerializeAttribute>();
                    if (baseAttribute != null)
                    {
                        if (baseAttribute.IsBaseType)
                        {
                            methodInfo        = SerializeMethodCache.BaseSerializeMethod.MakeGenericMethod(baseType, type);
                            DefaultSerializer = (Action <Serializer, valueType>)Delegate.CreateDelegate(typeof(Action <Serializer, valueType>), methodInfo);
                            return;
                        }
                        break;
                    }
                }
            }
            isJson      = attribute.GetIsJson;
            isMemberMap = attribute.GetIsMemberMap;
            Fields <FieldSize> fields = SerializeMethodCache.GetFields(attribute.IsAnonymousFields ? MemberIndexGroup <valueType> .GetAnonymousFields(attribute.MemberFilters) : MemberIndexGroup <valueType> .GetFields(attribute.MemberFilters), isJson, out memberCountVerify);
            //if (!type.IsValueType && (fields.FixedFields.length | fields.Fields.length | fields.JsonFields.length) == 0)
            //{
            //    DefaultSerializer = noMember;
            //    isValueType = true;
            //    IsReferenceMember = false;
            //    return;
            //}
            fixedFillSize = -fields.FixedSize & 3;
            fixedSize     = (fields.FixedSize + (sizeof(int) + 3)) & (int.MaxValue - 3);
#if NOJIT
            fixedMemberSerializer = new FieldFerializer(ref fields.FixedFields).Serialize;
            if (isMemberMap)
            {
                fixedMemberMapSerializer = new MemberMapSerializer(ref fields.FixedFields).Serialize;
            }
            if (fields.FieldArray.Length != 0)
            {
                memberSerializer = new FieldFerializer(ref fields.FieldArray).Serialize;
                if (isMemberMap)
                {
                    memberMapSerializer = new MemberMapSerializer(ref fields.FieldArray).Serialize;
                }
            }
#else
            SerializeMemberDynamicMethod    fixedDynamicMethod          = new SerializeMemberDynamicMethod(type);
            SerializeMemberMapDynamicMethod fixedMemberMapDynamicMethod = isMemberMap ? new SerializeMemberMapDynamicMethod(type) : default(SerializeMemberMapDynamicMethod);
            foreach (FieldSize member in fields.FixedFields)
            {
                fixedDynamicMethod.Push(member);
                if (isMemberMap)
                {
                    fixedMemberMapDynamicMethod.Push(member);
                }
            }
            fixedMemberSerializer = (Action <Serializer, valueType>)fixedDynamicMethod.Create <Action <Serializer, valueType> >();
            if (isMemberMap)
            {
                fixedMemberMapSerializer = (Action <MemberMap, Serializer, valueType>)fixedMemberMapDynamicMethod.Create <Action <MemberMap, Serializer, valueType> >();
            }

            if (fields.FieldArray.Length != 0)
            {
                SerializeMemberDynamicMethod    dynamicMethod          = new SerializeMemberDynamicMethod(type);
                SerializeMemberMapDynamicMethod memberMapDynamicMethod = isMemberMap ? new SerializeMemberMapDynamicMethod(type) : default(SerializeMemberMapDynamicMethod);
                foreach (FieldSize member in fields.FieldArray)
                {
                    dynamicMethod.Push(member);
                    if (isMemberMap)
                    {
                        memberMapDynamicMethod.Push(member);
                    }
                }
                memberSerializer = (Action <Serializer, valueType>)dynamicMethod.Create <Action <Serializer, valueType> >();
                if (isMemberMap)
                {
                    memberMapSerializer = (Action <MemberMap, Serializer, valueType>)memberMapDynamicMethod.Create <Action <MemberMap, Serializer, valueType> >();
                }
            }
#endif
            if (fields.JsonFields.Length != 0)
            {
                jsonMemberMap    = new MemberMap <valueType>();
                jsonMemberIndexs = new int[fields.JsonFields.Length];
                int index = 0;
                foreach (FieldIndex field in fields.JsonFields)
                {
                    jsonMemberMap.SetMember(jsonMemberIndexs[index++] = field.MemberIndex);
                }
            }
        }
Пример #11
0
        static TypeSerializer()
        {
            Type       type       = typeof(valueType);
            MethodInfo methodInfo = Serializer.GetSerializeMethod(type);

            if (methodInfo != null)
            {
                defaultSerializer = (Action <Serializer, valueType>)Delegate.CreateDelegate(typeof(Action <Serializer, valueType>), methodInfo);
                isValueType       = true;
                return;
            }
            if (type.IsArray)
            {
                //if (type.GetArrayRank() == 1) defaultSerializer = (Action<Serializer, valueType>)Delegate.CreateDelegate(typeof(Action<Serializer, valueType>), SerializeMethodCache.GetArray(type.GetElementType()));
                if (type.GetArrayRank() == 1)
                {
                    Type elementType = type.GetElementType();
                    if (elementType.IsValueType && (!elementType.IsGenericType || elementType.GetGenericTypeDefinition() != typeof(Nullable <>)))
                    {
                        defaultSerializer = (Action <Serializer, valueType>)Delegate.CreateDelegate(typeof(Action <Serializer, valueType>), StructGenericType.Get(elementType).JsonSerializeStructArrayMethod);
                    }
                    else
                    {
                        defaultSerializer = (Action <Serializer, valueType>)Delegate.CreateDelegate(typeof(Action <Serializer, valueType>), GenericType.Get(elementType).JsonSerializeArrayMethod);
                    }
                }
                else
                {
                    defaultSerializer = arrayManyRank;
                }
                isValueType = true;
                return;
            }
            if (type.IsEnum)
            {
                defaultSerializer = enumToString;
                isValueType       = true;
                return;
            }
            if (type.IsInterface || type.IsPointer || typeof(Delegate).IsAssignableFrom(type))
            {
                defaultSerializer = toNull;
                isValueType       = true;
                return;
            }
            if (type.IsGenericType)
            {
                Type genericType = type.GetGenericTypeDefinition();
                if (genericType == typeof(Dictionary <,>))
                {
                    defaultSerializer = (Action <Serializer, valueType>)Delegate.CreateDelegate(typeof(Action <Serializer, valueType>), SerializeMethodCache.GetDictionary(type));
                    isValueType       = true;
                    return;
                }
                if (genericType == typeof(Nullable <>))
                {
                    //defaultSerializer = (Action<Serializer, valueType>)Delegate.CreateDelegate(typeof(Action<Serializer, valueType>), SerializeMethodCache.GetNullable(type));
                    defaultSerializer = (Action <Serializer, valueType>)Delegate.CreateDelegate(typeof(Action <Serializer, valueType>), StructGenericType.Get(type.GetGenericArguments()[0]).JsonSerializeNullableMethod);
                    isValueType       = true;
                    return;
                }
                if (genericType == typeof(KeyValuePair <,>))
                {
                    //defaultSerializer = (Action<Serializer, valueType>)Delegate.CreateDelegate(typeof(Action<Serializer, valueType>), SerializeMethodCache.GetKeyValuePair(type));
                    defaultSerializer = (Action <Serializer, valueType>)Delegate.CreateDelegate(typeof(Action <Serializer, valueType>), GenericType2.Get(type.GetGenericArguments()).JsonSerializeKeyValuePairMethod);
                    isValueType       = true;
                    return;
                }
            }
            if ((methodInfo = SerializeMethodCache.GetCustom(type)) != null)
            {
                if (type.IsValueType)
                {
#if NOJIT
                    defaultSerializer = new CustomSerializer(methodInfo).Serialize;
#else
                    DynamicMethod dynamicMethod = new DynamicMethod("CustomJsonSerializer", null, new Type[] { typeof(Serializer), type }, type, true);
                    ILGenerator   generator     = dynamicMethod.GetILGenerator();
                    generator.Emit(OpCodes.Ldarga_S, 1);
                    generator.Emit(OpCodes.Ldarg_0);
                    generator.call(methodInfo);
                    generator.Emit(OpCodes.Ret);
                    defaultSerializer = (Action <Serializer, valueType>)dynamicMethod.CreateDelegate(typeof(Action <Serializer, valueType>));
#endif
                }
                else
                {
                    defaultSerializer = (Action <Serializer, valueType>)Delegate.CreateDelegate(typeof(Action <Serializer, valueType>), methodInfo);
                }
                isValueType = true;
            }
            else if ((methodInfo = SerializeMethodCache.GetIEnumerable(type)) != null)
            {
                defaultSerializer = (Action <Serializer, valueType>)Delegate.CreateDelegate(typeof(Action <Serializer, valueType>), methodInfo);
                isValueType       = true;
            }
            else
            {
                Type attributeType;
                attribute = type.customAttribute <SerializeAttribute>(out attributeType) ?? (type.Name[0] == '<' ? SerializeAttribute.AnonymousTypeMember : Serializer.AllMemberAttribute);
                if (type.IsValueType)
                {
                    isValueType = true;
                }
                else if (attribute != Serializer.AllMemberAttribute && attributeType != type)
                {
                    for (Type baseType = type.BaseType; baseType != typeof(object); baseType = baseType.BaseType)
                    {
                        SerializeAttribute baseAttribute = baseType.customAttribute <SerializeAttribute>();
                        if (baseAttribute != null)
                        {
                            if (baseAttribute.IsBaseType)
                            {
                                methodInfo        = SerializeMethodCache.BaseSerializeMethod.MakeGenericMethod(baseType, type);
                                defaultSerializer = (Action <Serializer, valueType>)Delegate.CreateDelegate(typeof(Action <Serializer, valueType>), methodInfo);
                                return;
                            }
                            break;
                        }
                    }
                }
                LeftArray <FieldIndex> fields = SerializeMethodCache.GetFields(MemberIndexGroup <valueType> .GetFields(attribute.MemberFilters), attribute);
                LeftArray <KeyValue <PropertyIndex, MethodInfo> > properties = SerializeMethodCache.GetProperties(MemberIndexGroup <valueType> .GetProperties(attribute.MemberFilters), attribute);
                bool isBox = false;
                if (type.IsValueType && fields.Length + properties.Length == 1)
                {
                    BoxSerializeAttribute boxSerialize = AutoCSer.Metadata.TypeAttribute.GetAttribute <BoxSerializeAttribute>(type);
                    if (boxSerialize != null && boxSerialize.IsJson)
                    {
                        isBox = true;
                    }
                }
#if AutoCSer
                AutoCSer.WebView.ClientTypeAttribute clientType = isBox ? null : AutoCSer.Metadata.TypeAttribute.GetAttribute <AutoCSer.WebView.ClientTypeAttribute>(type);
                if (clientType != null)
                {
                    if (clientType.MemberName == null)
                    {
                        viewClientTypeName = "new " + clientType.GetClientName(type) + "({";
                    }
                    else
                    {
                        viewClientTypeName = clientType.GetClientName(type) + ".Get({";
                    }
                }
#endif
#if NOJIT
                if (isBox)
                {
                    defaultSerializer = memberSerializer = new FieldPropertySerializer(ref fields, ref properties).SerializeBox;
                }
                else
                {
                    memberSerializer    = new FieldPropertySerializer(ref fields, ref properties).Serialize;
                    memberMapSerializer = new MemberMapSerializer(ref fields, ref properties).Serialize;
                }
#else
                SerializeMemberDynamicMethod    dynamicMethod          = new SerializeMemberDynamicMethod(type);
                SerializeMemberMapDynamicMethod memberMapDynamicMethod = isBox ? default(SerializeMemberMapDynamicMethod) : new SerializeMemberMapDynamicMethod(type);
                foreach (FieldIndex member in fields)
                {
                    if (isBox)
                    {
                        dynamicMethod.PushBox(member);
                    }
                    else
                    {
                        dynamicMethod.Push(member);
                        memberMapDynamicMethod.Push(member);
                    }
                }
                foreach (KeyValue <PropertyIndex, MethodInfo> member in properties)
                {
                    if (isBox)
                    {
                        dynamicMethod.PushBox(member.Key, member.Value);
                    }
                    else
                    {
                        dynamicMethod.Push(member.Key, member.Value);
                        memberMapDynamicMethod.Push(member.Key, member.Value);
                    }
                }
                memberSerializer = (Action <Serializer, valueType>)dynamicMethod.Create <Action <Serializer, valueType> >();
                if (isBox)
                {
                    defaultSerializer = memberSerializer;
                }
                else
                {
                    memberMapSerializer = (Action <MemberMap, Serializer, valueType, CharStream>)memberMapDynamicMethod.Create <Action <MemberMap, Serializer, valueType, CharStream> >();
                }
#endif
            }
        }
Пример #12
0
        static TypeSerializer()
        {
            Type       type       = typeof(valueType);
            MethodInfo methodInfo = XmlSerializer.GetSerializeMethod(type);

            if (methodInfo != null)
            {
                defaultSerializer = (Action <XmlSerializer, valueType>)Delegate.CreateDelegate(typeof(Action <XmlSerializer, valueType>), methodInfo);
                isValueType       = true;
                return;
            }
            if (type.IsArray)
            {
                if (type.GetArrayRank() == 1)
                {
                    defaultSerializer = (Action <XmlSerializer, valueType>)SerializeMethodCache.GetArray(type.GetElementType());
                }
                else
                {
                    defaultSerializer = ignore;
                }
                isValueType = true;
                return;
            }
            if (type.IsEnum)
            {
                defaultSerializer = enumToString;
                isValueType       = true;
                return;
            }
            if (type.IsInterface || type.IsPointer || typeof(Delegate).IsAssignableFrom(type))
            {
                defaultSerializer = ignore;
                isValueType       = true;
                return;
            }
            if (type.IsGenericType)
            {
                Type genericType = type.GetGenericTypeDefinition();
                if (genericType == typeof(Nullable <>))
                {
                    defaultSerializer = (Action <XmlSerializer, valueType>)StructGenericType.Get(type.GetGenericArguments()[0]).XmlSerializeNullableMethod;
                    isValueType       = true;
                    return;
                }
            }
            if ((methodInfo = SerializeMethodCache.GetCustom(type)) != null)
            {
                if (type.IsValueType)
                {
#if NOJIT
                    defaultSerializer = new CustomSerializer(methodInfo).Serialize;
#else
                    DynamicMethod dynamicMethod = new DynamicMethod("CustomXmlSerializer", null, new Type[] { typeof(XmlSerializer), type }, type, true);
                    ILGenerator   generator     = dynamicMethod.GetILGenerator();
                    generator.Emit(OpCodes.Ldarga_S, 1);
                    generator.Emit(OpCodes.Ldarg_0);
                    generator.call(methodInfo);
                    generator.Emit(OpCodes.Ret);
                    defaultSerializer = (Action <XmlSerializer, valueType>)dynamicMethod.CreateDelegate(typeof(Action <XmlSerializer, valueType>));
#endif
                }
                else
                {
                    defaultSerializer = (Action <XmlSerializer, valueType>)Delegate.CreateDelegate(typeof(Action <XmlSerializer, valueType>), methodInfo);
                }
                isValueType = true;
            }
            else
            {
                Delegate enumerableDelegate = SerializeMethodCache.GetIEnumerable(type);
                if (enumerableDelegate != null)
                {
                    defaultSerializer = (Action <XmlSerializer, valueType>)enumerableDelegate;
                    isValueType       = true;
                }
                else
                {
                    Type attributeType;
                    attribute = type.customAttribute <XmlSerializeAttribute>(out attributeType) ?? (type.Name[0] == '<' ? XmlSerializeAttribute.AnonymousTypeMember : XmlSerializer.DefaultAttribute);
                    if (type.IsValueType)
                    {
                        isValueType = true;
                    }
                    else if (attribute != XmlSerializer.DefaultAttribute && attributeType != type)
                    {
                        for (Type baseType = type.BaseType; baseType != typeof(object); baseType = baseType.BaseType)
                        {
                            XmlSerializeAttribute baseAttribute = baseType.customAttribute <XmlSerializeAttribute>();
                            if (baseAttribute != null)
                            {
                                if (baseAttribute.IsBaseType)
                                {
                                    methodInfo        = SerializeMethodCache.BaseSerializeMethod.MakeGenericMethod(baseType, type);
                                    defaultSerializer = (Action <XmlSerializer, valueType>)Delegate.CreateDelegate(typeof(Action <XmlSerializer, valueType>), methodInfo);
                                    return;
                                }
                                break;
                            }
                        }
                    }
                    LeftArray <KeyValue <FieldIndex, XmlSerializeMemberAttribute> > fields = SerializeMethodCache.GetFields(MemberIndexGroup <valueType> .GetFields(attribute.MemberFilters), attribute);
                    LeftArray <PropertyMethod> properties = SerializeMethodCache.GetProperties(MemberIndexGroup <valueType> .GetProperties(attribute.MemberFilters), attribute);
                    bool isBox = false;
                    if (type.IsValueType && fields.Length + properties.Length == 1)
                    {
                        BoxSerializeAttribute boxSerialize = AutoCSer.Metadata.TypeAttribute.GetAttribute <BoxSerializeAttribute>(type);
                        if (boxSerialize != null && boxSerialize.IsXml)
                        {
                            isBox = true;
                        }
                    }
#if NOJIT
                    if (isBox)
                    {
                        defaultSerializer = memberSerializer = new FieldPropertySerializer(ref fields, ref properties).SerializeBox;
                    }
                    else
                    {
                        memberSerializer    = new FieldPropertySerializer(ref fields, ref properties).Serialize;
                        memberMapSerializer = new MemberMapSerializer(ref fields, ref properties).Serialize;
                    }
#else
                    SerializeMemberDynamicMethod    dynamicMethod          = new SerializeMemberDynamicMethod(type);
                    SerializeMemberMapDynamicMethod memberMapDynamicMethod = isBox ? default(SerializeMemberMapDynamicMethod) : new SerializeMemberMapDynamicMethod(type);
                    foreach (KeyValue <FieldIndex, XmlSerializeMemberAttribute> member in fields)
                    {
                        if (isBox)
                        {
                            dynamicMethod.PushBox(member.Key);
                        }
                        else
                        {
                            dynamicMethod.Push(member.Key, member.Value);
                            memberMapDynamicMethod.Push(member.Key, member.Value);
                        }
                    }
                    foreach (PropertyMethod member in properties)
                    {
                        if (isBox)
                        {
                            dynamicMethod.PushBox(member.Property, member.Method);
                        }
                        else
                        {
                            dynamicMethod.Push(member.Property, member.Method, member.Attribute);
                            memberMapDynamicMethod.Push(member.Property, member.Method, member.Attribute);
                        }
                    }
                    memberSerializer = (Action <XmlSerializer, valueType>)dynamicMethod.Create <Action <XmlSerializer, valueType> >();
                    if (isBox)
                    {
                        defaultSerializer = memberSerializer;
                    }
                    else
                    {
                        memberMapSerializer = (Action <MemberMap, XmlSerializer, valueType>)memberMapDynamicMethod.Create <Action <MemberMap, XmlSerializer, valueType> >();
                    }
#endif
                }
            }
        }
Пример #13
0
            /// <summary>
            /// 安装下一个类型
            /// </summary>
            protected unsafe override void nextCreate()
            {
                if (Type.Type.IsClass && !Type.Type.IsAbstract)
                {
                    LeftArray <TcpMethod> methodArray = new LeftArray <TcpMethod>(Metadata.MethodIndex.GetMethods <AutoCSer.Net.TcpServer.MethodAttribute>(Type, Attribute.GetMemberFilters, false, Attribute.IsAttribute, Attribute.IsBaseTypeAttribute)
                                                                                  .getFind(value => !value.Method.IsGenericMethod)
                                                                                  .getArray(value => new TcpMethod
                    {
                        Method           = value,
                        MethodType       = Type,
                        ServiceAttribute = Attribute
                    }));
                    foreach (MemberIndexInfo member in MemberIndexGroup.Get <AutoCSer.Net.TcpServer.MethodAttribute>(Type, Attribute.GetMemberFilters, false, Attribute.IsAttribute, Attribute.IsBaseTypeAttribute))
                    {
                        if (member.IsField)
                        {
                            FieldInfo field     = (FieldInfo)member.Member;
                            TcpMethod getMethod = new TcpMethod
                            {
                                Method           = new Metadata.MethodIndex(field, true),
                                MemberIndex      = member,
                                MethodType       = Type,
                                ServiceAttribute = Attribute
                            };
                            if (!getMethod.Attribute.IsOnlyGetMember)
                            {
                                getMethod.SetMethod = new TcpMethod {
                                    Method = new MethodIndex(field, false), MemberIndex = member, MethodType = Type, ServiceAttribute = Attribute
                                };
                            }
                            methodArray.Add(getMethod);
                            if (getMethod.SetMethod != null)
                            {
                                methodArray.Add(getMethod.SetMethod);
                            }
                        }
                        else if (member.CanGet)
                        {
                            PropertyInfo property  = (PropertyInfo)member.Member;
                            TcpMethod    getMethod = new TcpMethod
                            {
                                Method           = new MethodIndex(property, true),
                                MemberIndex      = member,
                                MethodType       = Type,
                                ServiceAttribute = Attribute
                            };
                            if (member.CanSet && !getMethod.Attribute.IsOnlyGetMember)
                            {
                                getMethod.SetMethod = new TcpMethod {
                                    Method = new MethodIndex(property, false), MemberIndex = member, MethodType = Type, ServiceAttribute = Attribute
                                };
                            }
                            methodArray.Add(getMethod);
                            if (getMethod.SetMethod != null)
                            {
                                methodArray.Add(getMethod.SetMethod);
                            }
                        }
                    }
                    MethodIndexs = methodArray.ToArray();
                    MethodIndexs = TcpMethod.CheckIdentity(MethodIndexs, Attribute.CommandIdentityEnmuType, getRememberIdentityName(Attribute.CommandIdentityEnmuType == null ? Attribute.GenericType ?? Type : null), method => method.Method.MethodKeyFullName);
                    if (MethodIndexs == null)
                    {
                        return;
                    }
                    int methodIndex = CallQueueCount = 0;
                    IsVerifyMethod  = false;
                    IsCallQueueLink = ServiceAttribute.GetRemoteExpressionServerTask == Net.TcpServer.ServerTaskType.QueueLink;
                    if (ServiceAttribute.GetRemoteExpressionServerTask == Net.TcpServer.ServerTaskType.Queue || ServiceAttribute.GetRemoteExpressionServerTask == Net.TcpServer.ServerTaskType.QueueLink)
                    {
                        CallQueueCount = (int)ServiceAttribute.GetRemoteExpressionCallQueueIndex + 1;
                    }
                    ParameterBuilder parameterBuilder = new ParameterBuilder {
                        IsSimpleSerialize = Attribute.IsSimpleSerialize
                    };
                    QueueTypeBuilder queueTypeBuilder = new QueueTypeBuilder();
                    foreach (TcpMethod method in MethodIndexs)
                    {
                        method.MethodIndex = methodIndex++;
                        if (!method.IsNullMethod)
                        {
                            if (IsVerifyMethod)
                            {
                                method.Attribute.IsVerifyMethod = false;
                            }
                            else if (method.IsVerifyMethod)
                            {
                                IsVerifyMethod            = true;
                                IsSynchronousVerifyMethod = method.Attribute.ServerTaskType == AutoCSer.Net.TcpServer.ServerTaskType.Synchronous && !method.IsAsynchronousCallback;
                                //method.Attribute.ServerTaskType = Net.TcpServer.ServerTaskType.Synchronous;
                            }
                            parameterBuilder.Add(method);
                            queueTypeBuilder.Add(method);

                            IsCallQueueLink |= method.Attribute.ServerTaskType == Net.TcpServer.ServerTaskType.QueueLink;
                            if (method.Attribute.ServerTaskType == Net.TcpServer.ServerTaskType.Queue || method.Attribute.ServerTaskType == Net.TcpServer.ServerTaskType.QueueLink)
                            {
                                CallQueueCount = Math.Max((int)method.Attribute.GetServerQueueIndex + 1, CallQueueCount);
                            }
                            MaxTimeoutSeconds = Math.Max(MaxTimeoutSeconds, method.Attribute.GetClientTimeoutSeconds);
                            //if (method.IsAsynchronousCallback && method.Attribute.ServerTaskType != Net.TcpServer.ServerTaskType.Synchronous)
                            //{
                            //    Messages.Message("异步函数警告" + method.MemberFullName);
                            //}
                        }
                    }
                    ParameterTypes       = parameterBuilder.Get();
                    ServerCallQueueTypes = queueTypeBuilder.Get();
                    //TcpMethod[] methodIndexs = MethodIndexs.getFindArray(value => !value.IsNullMethod);
                    if (ServiceAttribute.GetIsSegmentation)
                    {
                        IsClientCode        = false;
                        create(IsServerCode = true);
                        CSharpTypeDefinition definition = new CSharpTypeDefinition(Type, IsClientCode = true, false, Type.Type.Namespace + ".TcpClient");
                        _code_.Length = 0;
                        _code_.Add(definition.Start);
                        create(IsServerCode = false);
                        _code_.Add(definition.End);
                        string fileName   = AutoParameter.ProjectPath + "{" + AutoParameter.DefaultNamespace + "}.TcpInternalServer." + ServerName + ".Client.cs";
                        string clientCode = Coder.WarningCode + _code_.ToString() + Coder.FileEndCode;
                        if (Coder.WriteFile(fileName, clientCode))
                        {
                            if (ServiceAttribute.ClientSegmentationCopyPath != null)
                            {
                                string copyFileName = ServiceAttribute.ClientSegmentationCopyPath + "{" + AutoParameter.DefaultNamespace + "}.TcpInternalServer." + ServerName + ".Client.cs";
                                if (Coder.WriteFile(copyFileName, clientCode))
                                {
                                    Messages.Message(copyFileName + " 被修改");
                                }
                            }
                            Messages.Message(fileName + " 被修改");
                        }
                    }
                    else
                    {
                        create(IsServerCode = IsClientCode = true);
                    }
                }
            }
Пример #14
0
        static TypeDeSerializer()
        {
            Type       type       = typeof(T);
            MethodInfo methodInfo = JsonDeSerializer.GetDeSerializeMethod(type);

            if (methodInfo != null)
            {
                DefaultDeSerializer = (JsonDeSerializer.DeSerializeDelegate <T>)Delegate.CreateDelegate(typeof(JsonDeSerializer.DeSerializeDelegate <T>), methodInfo);
                return;
            }
            if (type.IsArray)
            {
                if (type.GetArrayRank() == 1)
                {
                    DefaultDeSerializer = (JsonDeSerializer.DeSerializeDelegate <T>)GenericType.Get(type.GetElementType()).JsonDeSerializeArrayMethod;
                }
                else
                {
                    DefaultDeSerializer = (JsonDeSerializer.DeSerializeDelegate <T>)GenericType.Get(type).JsonDeSerializeNotSupportDelegate;
                }
                return;
            }
            if (type.IsEnum)
            {
                if (type.IsDefined(typeof(FlagsAttribute), false))
                {
                    DefaultDeSerializer = (JsonDeSerializer.DeSerializeDelegate <T>)EnumGenericType.Get(type).JsonDeSerializeEnumFlagsDelegate;
                }
                else
                {
                    DefaultDeSerializer = (JsonDeSerializer.DeSerializeDelegate <T>)EnumGenericType.Get(type).JsonDeSerializeEnumDelegate;
                }
                return;
            }
            if (type.isSerializeNotSupport())
            {
                DefaultDeSerializer = (JsonDeSerializer.DeSerializeDelegate <T>)GenericType.Get(type).JsonDeSerializeNotSupportDelegate;
                return;
            }
            if (type.IsGenericType)
            {
                Type genericType = type.GetGenericTypeDefinition();
                if (genericType == typeof(Dictionary <,>))
                {
                    DefaultDeSerializer = (JsonDeSerializer.DeSerializeDelegate <T>)GenericType2.Get(type.GetGenericArguments()).JsonDeSerializeDictionaryMethod;
                    return;
                }
                if (genericType == typeof(Nullable <>))
                {
                    DefaultDeSerializer = (JsonDeSerializer.DeSerializeDelegate <T>)DeSerializeMethodCache.GetNullable(type);
                    return;
                }
                if (genericType == typeof(KeyValuePair <,>))
                {
                    DefaultDeSerializer = (JsonDeSerializer.DeSerializeDelegate <T>)GenericType2.Get(type.GetGenericArguments()).JsonDeSerializeKeyValuePairMethod;
                    isValueType         = true;
                    return;
                }
            }
            if ((methodInfo = DeSerializeMethodCache.GetCustom(type)) != null)
            {
                if (type.IsValueType)
                {
#if NOJIT
                    DefaultDeSerializer = new CustomDeSerializer(methodInfo).DeSerialize;
#else
                    DynamicMethod dynamicMethod = new DynamicMethod("CustomJsonDeSerializer", null, new Type[] { typeof(JsonDeSerializer), type.MakeByRefType() }, type, true);
                    ILGenerator   generator     = dynamicMethod.GetILGenerator();
                    generator.Emit(OpCodes.Ldarg_1);
                    generator.Emit(OpCodes.Ldarg_0);
                    generator.call(methodInfo);
                    generator.Emit(OpCodes.Ret);
                    DefaultDeSerializer = (JsonDeSerializer.DeSerializeDelegate <T>)dynamicMethod.CreateDelegate(typeof(JsonDeSerializer.DeSerializeDelegate <T>));
#endif
                }
                else
                {
                    DefaultDeSerializer = (JsonDeSerializer.DeSerializeDelegate <T>)Delegate.CreateDelegate(typeof(JsonDeSerializer.DeSerializeDelegate <T>), methodInfo);
                }
            }
            else
            {
                Type attributeType;
                attribute = type.customAttribute <JsonDeSerializeAttribute>(out attributeType) ?? JsonDeSerializer.AllMemberAttribute;
                if ((methodInfo = DeSerializeMethodCache.GetIEnumerableConstructor(type)) != null)
                {
                    DefaultDeSerializer = (JsonDeSerializer.DeSerializeDelegate <T>)Delegate.CreateDelegate(typeof(JsonDeSerializer.DeSerializeDelegate <T>), methodInfo);
                }
                else
                {
                    if (type.IsValueType)
                    {
                        isValueType = true;
                    }
                    else if (attribute != JsonDeSerializer.AllMemberAttribute && attributeType != type)
                    {
                        for (Type baseType = type.BaseType; baseType != typeof(object); baseType = baseType.BaseType)
                        {
                            JsonDeSerializeAttribute baseAttribute = baseType.customAttribute <JsonDeSerializeAttribute>();
                            if (baseAttribute != null)
                            {
                                if (baseAttribute.IsBaseType)
                                {
                                    methodInfo          = DeSerializeMethodCache.BaseDeSerializeMethod.MakeGenericMethod(baseType, type);
                                    DefaultDeSerializer = (JsonDeSerializer.DeSerializeDelegate <T>)Delegate.CreateDelegate(typeof(JsonDeSerializer.DeSerializeDelegate <T>), methodInfo);
                                    return;
                                }
                                break;
                            }
                        }
                    }
                    FieldIndex             defaultMember = null;
                    LeftArray <FieldIndex> fields        = DeSerializeMethodCache.GetFields(MemberIndexGroup <T> .GetFields(attribute.MemberFilters), attribute, ref defaultMember);
                    LeftArray <KeyValue <PropertyIndex, MethodInfo> > properties = DeSerializeMethodCache.GetProperties(MemberIndexGroup <T> .GetProperties(attribute.MemberFilters), attribute);
                    bool isBox = false;
                    if (type.IsValueType && fields.Length + properties.Length == 1)
                    {
                        BoxSerializeAttribute boxSerialize = AutoCSer.Metadata.TypeAttribute.GetAttribute <BoxSerializeAttribute>(type);
                        if (boxSerialize != null && boxSerialize.IsJson)
                        {
                            isBox         = true;
                            defaultMember = null;
                        }
                    }
                    TryDeSerializeFilter[] deSerializers = new TryDeSerializeFilter[fields.Length + properties.Length + (defaultMember == null ? 0 : 1)];
                    //memberMap.type memberMapType = memberMap<valueType>.TypeInfo;
                    string[] names = isBox ? null : new string[deSerializers.Length];
#if !NOJIT
                    DeSerializeDynamicMethod dynamicMethod = isBox ? default(DeSerializeDynamicMethod) : new DeSerializeDynamicMethod(type, false), memberMapDynamicMethod = isBox ? default(DeSerializeDynamicMethod) : new DeSerializeDynamicMethod(type, true);
#endif
                    int index = 0, nameLength = 0, maxNameLength = 0;
                    foreach (FieldIndex member in fields)
                    {
                        TryDeSerializeFilter tryDeSerialize = deSerializers[index] = new TryDeSerializeFilter
                        {
#if NOJIT
                            TryDeSerialize = new FieldDeSerializer(member.Member).DeSerializer(),
#else
                            TryDeSerialize = (JsonDeSerializer.DeSerializeDelegate <T>)DeSerializeMethodCache.CreateDynamicMethod(type, member.Member).CreateDelegate(typeof(JsonDeSerializer.DeSerializeDelegate <T>)),
#endif
                            MemberMapIndex = member.MemberIndex,
                            //MemberFilters = member.Member.IsPublic ? Metadata.MemberFilters.PublicInstanceField : Metadata.MemberFilters.NonPublicInstanceField
                        };
                        if (!isBox)
                        {
#if !NOJIT
                            dynamicMethod.Push(member);
                            memberMapDynamicMethod.Push(member);
#endif
                            string name = member.AnonymousName;
                            if (name.Length > maxNameLength)
                            {
                                maxNameLength = name.Length;
                            }
                            nameLength += (names[index++] = name).Length;
                            if (member == defaultMember)
                            {
                                deSerializers[deSerializers.Length - 1] = tryDeSerialize;
                                names[deSerializers.Length - 1]         = string.Empty;
                            }
                        }
                    }
                    foreach (KeyValue <PropertyIndex, MethodInfo> member in properties)
                    {
                        deSerializers[index] = new TryDeSerializeFilter
                        {
#if NOJIT
                            TryDeSerialize = new PropertyDeSerializer(member.Key.Member).DeSerializer(),
#else
                            TryDeSerialize = (JsonDeSerializer.DeSerializeDelegate <T>)DeSerializeMethodCache.CreateDynamicMethod(type, member.Key.Member, member.Value).CreateDelegate(typeof(JsonDeSerializer.DeSerializeDelegate <T>)),
#endif
                            MemberMapIndex = member.Key.MemberIndex,
                            //MemberFilters = member.Value.IsPublic ? Metadata.MemberFilters.PublicInstanceProperty : Metadata.MemberFilters.NonPublicInstanceProperty
                        };
                        if (!isBox)
                        {
#if !NOJIT
                            dynamicMethod.Push(member.Key, member.Value);
                            memberMapDynamicMethod.Push(member.Key, member.Value);
#endif
                            if (member.Key.Member.Name.Length > maxNameLength)
                            {
                                maxNameLength = member.Key.Member.Name.Length;
                            }
                            nameLength += (names[index++] = member.Key.Member.Name).Length;
                        }
                    }
                    if (isBox)
                    {
                        unboxDeSerializer   = deSerializers[0].TryDeSerialize;
                        DefaultDeSerializer = unbox;
                    }
                    else
                    {
#if !NOJIT
                        deSerializeMember    = (DeSerializeMember)dynamicMethod.Create <DeSerializeMember>();
                        deSerializeMemberMap = (DeSerializeMemberMap)memberMapDynamicMethod.Create <DeSerializeMemberMap>();
#endif
                        if (type.Name[0] == '<')
                        {
                            isAnonymousType = true;
                        }
                        if (maxNameLength > (short.MaxValue >> 1) - 4 || nameLength == 0)
                        {
                            memberNames = Unmanaged.NullByte8;
                        }
                        else
                        {
                            memberNames = Unmanaged.GetStaticPointer((nameLength + (names.Length - (defaultMember == null ? 0 : 1)) * 5 + 1) << 1, false);
                            byte *write = memberNames.Byte;
                            foreach (string name in names)
                            {
                                if (name.Length != 0)
                                {
                                    if (write == memberNames.Byte)
                                    {
                                        *(short *)write = (short)((name.Length + 3) * sizeof(char));
                                        *(char *)(write + sizeof(short)) = '"';
                                        write += sizeof(short) + sizeof(char);
                                    }
                                    else
                                    {
                                        *(short *)write = (short)((name.Length + 4) * sizeof(char));
                                        *(int *)(write + sizeof(short)) = ',' + ('"' << 16);
                                        write += sizeof(short) + sizeof(int);
                                    }
                                    fixed(char *nameFixed = name) AutoCSer.Extensions.StringExtension.SimpleCopyNotNull(nameFixed, (char *)write, name.Length);

                                    *(int *)(write += name.Length << 1) = '"' + (':' << 16);
                                    write += sizeof(int);
                                }
                            }
                            *(short *)write = 0;
                        }
                        memberSearcher      = new StateSearcher(StateSearcher.GetMemberSearcher(type, names));
                        memberDeSerializers = deSerializers;

                        Type refType = type.MakeByRefType();
                        foreach (AutoCSer.Metadata.AttributeMethod attributeMethod in AutoCSer.Metadata.AttributeMethod.GetStatic(type))
                        {
                            if ((methodInfo = attributeMethod.Method).ReturnType == typeof(void))
                            {
                                ParameterInfo[] parameters = methodInfo.GetParameters();
                                if (parameters.Length == 3 && parameters[0].ParameterType == typeof(JsonDeSerializer) && parameters[1].ParameterType == refType && parameters[2].ParameterType == Emit.Pub.PointerSizeRefType)
                                {
                                    if (attributeMethod.GetAttribute <JsonDeSerializeUnknownNameAttriubte>() != null)
                                    {
                                        onUnknownName = (UnknownDeSerialize)Delegate.CreateDelegate(typeof(UnknownDeSerialize), methodInfo);
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Пример #15
0
        static Copyer()
        {
            Type type = typeof(valueType), refType = type.MakeByRefType();

            if (!type.IsValueType)
            {
                memberwiseClone = (Func <valueType, object>)Delegate.CreateDelegate(typeof(Func <valueType, object>), typeof(object).GetMethod("MemberwiseClone", BindingFlags.Instance | BindingFlags.NonPublic));
            }
            if (type.IsArray)
            {
                if (type.GetArrayRank() == 1)
                {
                    Type copyerType = typeof(Copyer <>).MakeGenericType(type.GetElementType());
                    defaultCopyer       = (copyer)Delegate.CreateDelegate(typeof(copyer), copyerType.GetMethod("copyArray", BindingFlags.Static | BindingFlags.NonPublic, null, new Type[] { refType, type }, null));
                    defaultMemberCopyer = (memberMapCopyer)Delegate.CreateDelegate(typeof(memberMapCopyer), copyerType.GetMethod("copyArray", BindingFlags.Static | BindingFlags.NonPublic, null, new Type[] { refType, type, typeof(MemberMap) }, null));
                    return;
                }
                defaultCopyer       = noCopy;
                defaultMemberCopyer = noCopy;
                return;
            }
            if (type.IsEnum || type.IsPointer || type.IsInterface || typeof(Delegate).IsAssignableFrom(type))
            {
                isValueCopy = true;
                return;
            }
            foreach (AutoCSer.Metadata.AttributeMethod methodInfo in AutoCSer.Metadata.AttributeMethod.GetStatic(type))
            {
                if (methodInfo.Method.ReturnType == typeof(void))
                {
                    ParameterInfo[] parameters = methodInfo.Method.GetParameters();
                    if (parameters.Length == 3 && parameters[0].ParameterType == refType && parameters[1].ParameterType == type && parameters[2].ParameterType == typeof(MemberMap))
                    {
                        if (methodInfo.GetAttribute <CustomAttribute>() != null)
                        {
                            defaultCopyer       = customCopy;
                            defaultMemberCopyer = (memberMapCopyer)Delegate.CreateDelegate(typeof(memberMapCopyer), methodInfo.Method);
                            return;
                        }
                    }
                }
            }
            FieldIndex[] fields = MemberIndexGroup <valueType> .GetFields();

            if (fields.Length == 0)
            {
                defaultCopyer       = noCopy;
                defaultMemberCopyer = noCopy;
                return;
            }
#if NOJIT
            defaultCopyer       = new FieldCopyer(fields).Copyer();
            defaultMemberCopyer = new MemberMapFieldCopyer(fields).Copyer();
#else
            MemberDynamicMethod dynamicMethod          = new MemberDynamicMethod(type, new DynamicMethod("MemberCopyer", null, new Type[] { refType, type }, type, true));
            MemberDynamicMethod memberMapDynamicMethod = new MemberDynamicMethod(type, new DynamicMethod("MemberMapCopyer", null, new Type[] { refType, type, typeof(MemberMap) }, type, true));
            foreach (FieldIndex field in fields)
            {
                dynamicMethod.Push(field);
                memberMapDynamicMethod.PushMemberMap(field);
            }
            defaultCopyer       = (copyer)dynamicMethod.Create <copyer>();
            defaultMemberCopyer = (memberMapCopyer)memberMapDynamicMethod.Create <memberMapCopyer>();
#endif
        }
Пример #16
0
        static HeaderQueryTypeParser()
        {
            Type type = typeof(valueType);

            AutoCSer.Json.ParseAttribute attribute = TypeAttribute.GetAttribute <AutoCSer.Json.ParseAttribute>(type, true) ?? AutoCSer.Json.Parser.AllMemberAttribute;
            FieldIndex             defaultMember   = null;
            LeftArray <FieldIndex> fields          = AutoCSer.Json.ParseMethodCache.GetFields(MemberIndexGroup <valueType> .GetFields(attribute.MemberFilters), attribute, ref defaultMember);
            LeftArray <KeyValue <PropertyIndex, MethodInfo> > properties = AutoCSer.Json.ParseMethodCache.GetProperties(MemberIndexGroup <valueType> .GetProperties(attribute.MemberFilters), attribute);

            memberParsers = new TryParse[fields.Length + properties.Length + (defaultMember == null ? 0 : 1)];
            string[] names = new string[memberParsers.Length];
            int      index = 0, nameLength = 0, maxNameLength = 0;

            foreach (FieldIndex member in fields)
            {
#if NOJIT
                TryParse tryParse = new HeaderQueryFieldParser(member.Member).Parser();
#else
                ILGenerator   generator;
                DynamicMethod memberDynamicMethod = HeaderQueryParser.CreateDynamicMethod(type, member.Member.Name, member.Member.FieldType, out generator);
                generator.Emit(OpCodes.Stfld, member.Member);
                generator.Emit(OpCodes.Ret);
                TryParse tryParse = (TryParse)memberDynamicMethod.CreateDelegate(typeof(TryParse));
#endif
                memberParsers[index] = tryParse;
                if (member.Member.Name.Length > maxNameLength)
                {
                    maxNameLength = member.Member.Name.Length;
                }
                nameLength += (names[index++] = member.Member.Name).Length;
                if (member == defaultMember)
                {
                    memberParsers[names.Length - 1] = tryParse;
                    names[names.Length - 1]         = string.Empty;
                }
            }
            foreach (KeyValue <PropertyIndex, MethodInfo> member in properties)
            {
#if NOJIT
                memberParsers[index] = new HeaderQueryPropertyParser(member.Key.Member).Parser();
#else
                ILGenerator   generator;
                DynamicMethod memberDynamicMethod = HeaderQueryParser.CreateDynamicMethod(type, member.Key.Member.Name, member.Key.Member.PropertyType, out generator);
                generator.call(member.Value);
                generator.Emit(OpCodes.Ret);
                memberParsers[index] = (TryParse)memberDynamicMethod.CreateDelegate(typeof(TryParse));
#endif
                if (member.Key.Member.Name.Length > maxNameLength)
                {
                    maxNameLength = member.Key.Member.Name.Length;
                }
                nameLength += (names[index++] = member.Key.Member.Name).Length;
            }
            if (maxNameLength > short.MaxValue || nameLength == 0)
            {
                memberNames = Unmanaged.NullByte8;
            }
            else
            {
                memberNames = new Pointer {
                    Data = Unmanaged.GetStatic(nameLength + (names.Length - (defaultMember == null ? 0 : 1)) * sizeof(short) + sizeof(short), false)
                };
                byte *write = memberNames.Byte;
                foreach (string name in names)
                {
                    if (name.Length != 0)
                    {
                        *(short *)write = (short)name.Length;

                        fixed(char *nameFixed = name) StringExtension.WriteBytesNotNull(nameFixed, name.Length, write + sizeof(short));

                        write += sizeof(short) + name.Length;
                    }
                }
                *(short *)write = 0;
            }
            memberSearcher = new HeaderQueryParseStateSearcher(AutoCSer.Json.StateSearcher.GetMemberSearcher(type, names));
        }