public void Write(object obj, bool serializeTypeName = false) { var type = obj.GetType(); writer.WriteBool(serializeTypeName); if (serializeTypeName) { writer.WriteString(type.FullName); } KarmaMap typeMap; if (!typeMapCache.TryGetValue(type, out typeMap)) { typeMap = new KarmaMap(type); typeMapCache.Add(type, typeMap); } var itemValueMap = typeMap.MapToValues( obj, null, (value) => { if (!options.SerializeDefaultValues) { return(value != null); } return(true); } ); writer.WriteInt32(itemValueMap.Count); foreach (var item in itemValueMap) { writer.WriteString(item.Item1.Name); if (item.Item2 == null) { writer.WriteBool(true); continue; } else { writer.WriteBool(false); WriteValue(item.Item2, item.Item1.MemberType.IsAbstract); } } }
public object ReadObject(Type type) { Type instanceType = type; if (reader.ReadBool()) { var typeName = reader.ReadString(); if (!typesCache.TryGetValue(typeName, out instanceType)) { instanceType = Type.GetType(typeName, false); if (instanceType != null) { typesCache[typeName] = instanceType; } else { for (int i = 0; i < assemblies.Length; ++i) { instanceType = assemblies[i].GetType(typeName); if (instanceType != null) { typesCache.Add(typeName, instanceType); break; } } } } } KarmaMap typeMap; if (!typeMapCache.TryGetValue(instanceType, out typeMap)) { typeMap = new KarmaMap(instanceType); typeMapCache.Add(instanceType, typeMap); } var instance = CreateTypeInstance(instanceType); var itemsCount = reader.ReadInt32(); for (int i = 0; i < itemsCount; ++i) { var itemName = reader.ReadString(); KarmaMapItem item; if (!typeMap.TryGetItem(itemName, out item)) { throw new KarmaException($"Data stream contains unknown member: {itemName}"); } var isNull = reader.ReadBool(); if (isNull) { item.SetValue(instance, null); continue; } item.SetValue(instance, ReadValue(item.MemberType)); } return(instance); }