コード例 #1
0
        /// <summary> Serializes the given <paramref name="element"/>. Note, if the element is NULL
        /// an empty array is returned.</summary>
        /// <param name="element">Element to serialize</param>
        /// <typeparam name="TObject">Type of element being serialized</typeparam>
        /// <returns>Serialized object</returns>
        public virtual byte[] Serialize <TObject>(TObject element) where TObject : class
        {
            if (element == null)
            {
                return(new byte[0]);
            }

            using (MemoryStream memoryStream = new MemoryStream()) {
                using (BinaryWriter binaryWriter = new BinaryWriter(memoryStream)) {
                    // First, we write the full qualified object type
                    Type   objType    = element.GetType();
                    string objTypeStr = objType.AssemblyQualifiedName;
                    binaryWriter.Write(objTypeStr);

                    // Then, we serialize the object itself
                    ISerializor serializor = GetSerializor(_excoSerializer, element);
                    serializor.WriteToStream(binaryWriter, element);
                }

                return(memoryStream.ToArray());
            }
        }
コード例 #2
0
        /// <summary> Deserializes an element from the given <paramref name="data"/>. Note, if
        /// the given data is NULL or empty, NULL is returned.</summary>
        /// <param name="data">Data of the object to deserialize</param>
        /// <returns>Deserialized element</returns>
        public virtual object Deserialize(byte[] data)
        {
            if (data == null || data.Length == 0)
            {
                return(null);
            }

            object element;

            using (MemoryStream memoryStream = new MemoryStream(data)) {
                using (BinaryReader binaryReader = new BinaryReader(memoryStream)) {
                    // First, we read the full qualified object type and create an object instance
                    string objTypeStr = binaryReader.ReadString();
                    Type   objType    = Type.GetType(objTypeStr, true);
                    element = objType.NewInstance <object>();

                    // Then, we deserialize the object itself
                    ISerializor serializor = GetSerializor(_excoSerializer, element);
                    serializor.ReadFromStream(binaryReader, element);
                }
            }

            return(element);
        }