/// <summary> /// Recursive method, serializing every object in my objects graph /// </summary> internal void Serialize(object obj, Type objType) { // If it's Object, we get the underlying type if (objType == typeof(Object) && obj != null) { var baseType = obj.GetType().GetBaseType(); var s = TypeSerializer.GetSerializer(baseType); Serialize(obj, baseType); return; } var serializer = TypeSerializer.GetSerializer(objType); // Write object type this.Writer.Write(objType.AssemblyQualifiedName); // Check if it's not a reference int refIndex = 0; DmState state = this.GetState(obj, objType, ref refIndex); // Write state this.Writer.Write((byte)state); // Write index; this.Writer.Write(refIndex); // if not null or ref if (state == DmState.IsAloneOrValue) { serializer.Serialize(this, obj, objType); } }
/// <summary> /// Recursive deserialise method to get every object from my stream /// </summary> internal Object GetObject(bool isDebugMode = false) { Object deserializedObject = null; int indent = 0; //if (this.Reader.BaseStream.Position >= this.Reader.BaseStream.Length) // throw new IndexOutOfRangeException("stream is ended !"); if (isDebugMode) { DebugWriter.WriteLineIndent(indent); DebugWriter.Write("{"); } // Get Type var objTypeFromStream = Reader.ReadString(); var objType = DmUtils.GetTypeFromAssemblyQualifiedName(objTypeFromStream); if (isDebugMode) { DebugWriter.Write($"[{objType.Name}]"); } // Get State and Index var state = (DmState)Reader.ReadByte(); var index = Reader.ReadInt32(); if (isDebugMode) { DebugWriter.Write($"[{state}][{index}]"); } TypeSerializer serializer = null; if (!typeSerializers.ContainsKey(objType)) { serializer = TypeSerializer.GetSerializer(objType); typeSerializers.Add(objType, serializer); } serializer = typeSerializers[objType]; if (state == DmState.IsReference) { deserializedObject = fromIndexes[index]; } else if (state != DmState.IsNull) { deserializedObject = serializer.Deserialize(this, objType, isDebugMode); // Dont make a reference on value type if (!objType.IsPrimitiveManagedType()) { fromIndexes.Add(index, deserializedObject); } } if (isDebugMode) { // cosmetic if (serializer.GetType() != typeof(PrimitiveSerializer)) { indent--; DebugWriter.WriteLineIndent(indent); } DebugWriter.Write("}"); } return(deserializedObject); }