private static void FillDataToCollection(XmlReader reader, object objectData, Dictionary <string, Type> typeMapping, Type elementType, Type parentType) { const string addMethodName = "Add"; int currentDepth = reader.Depth; bool isValueType = elementType.IsValueType || typeof(string).Equals(elementType) || elementType.IsEnum; // Type genericType = rawType.GetGenericArguments()[0]; Type genericType = ModuleUtils.GetRawGenericElementType(parentType); MethodInfo addMethod = parentType.GetMethod(addMethodName, BindingFlags.Instance | BindingFlags.Public, null, CallingConventions.Standard, new Type[] { genericType }, new ParameterModifier[0]); GenericCollectionAttribute collectionAttribute = elementType.GetCustomAttribute <GenericCollectionAttribute>(); reader.Read(); // xml层级等于或者小于父节点时说明集合已经遍历结束,停止遍历 // Reader的更新在Read while (reader.Depth > currentDepth) { // 如果不是节点或者是空节点或者是结束节点,则继续下一行读取 if (reader.NodeType != XmlNodeType.Element || (reader.IsEmptyElement && !reader.HasAttributes) || reader.NodeType == XmlNodeType.EndElement) { bool readNotOver = reader.Read(); if (!readNotOver) { return; } continue; } if (isValueType) { string value = reader.GetAttribute(Constants.ValueTypeName); if (null != value) { object element = ValueConvertor.ReadData(elementType, value); addMethod.Invoke(objectData, new object[] { element }); } // Value模式时需要手动去调整reader的位置 reader.Read(); } else { // 填充集合或者类时,reader的shift在FillDataToObject和FillDataToCollection中调用 object element = CreateTypeInstance(typeMapping, GetTypeName(elementType)); if (null == collectionAttribute) { FillDataToObject(reader, element, typeMapping); } else { FillDataToCollection(reader, element, typeMapping, collectionAttribute.GenericType, genericType); } addMethod.Invoke(objectData, new object[] { element }); } } // 如果是endElement则直接跳过 if (reader.NodeType == XmlNodeType.EndElement) { reader.Read(); } }
private static void FillValueToObject(PropertyInfo propertyInfo, object objectData, string attribute) { Type propertyType = propertyInfo.PropertyType; object value = null; if (propertyType.IsEnum) { value = EnumConvertor.ReadData(propertyType, attribute); } else { value = ValueConvertor.ReadData(propertyType, attribute); } if (null != value) { propertyInfo.SetValue(objectData, value); } }
public SerializableMap(SerializationInfo info, StreamingContext context) { this._innerCollection = new Dictionary <TKey, TValue>(UtilityConstants.DefaultEntityCount); SerializationInfoEnumerator enumerator = info.GetEnumerator(); while (enumerator.MoveNext()) { TKey key; Type keyType = typeof(TKey); if (keyType.IsEnum) { key = (TKey)EnumConvertor.ReadData(keyType, enumerator.Name); } else { key = (TKey)ValueConvertor.ReadData(keyType, enumerator.Name); } this._innerCollection.Add(key, (TValue)enumerator.Value); } }