Ejemplo n.º 1
0
        /// <summary>
        /// Serialize an object
        /// </summary>
        /// <typeparam name="T">Any reference type</typeparam>
        /// <param name="obj">Object to serialize</param>
        /// <param name="options">Serialization options</param>
        /// <returns>Byte array containing the serialized object</returns>
        public static byte[] Serialize <T>(T obj, SerializationOptions options)
        {
            using (var ms = new MemoryStream())
            {
                if (obj == null)
                {
                    return(new byte[0]);
                }

                object objToSerialize = ObjectCleaner.PrepareObjectForSerialization(obj);
                var    cargo          = new SerializerObjectTracker();


                var serializerMethod       = GetTypeToObjectSerializer(obj.GetType());
                var stringSerializerMethod = (Action <Stream, string, SerializerObjectTracker>)GetTypeSerializer(typeof(string));
                var intSerializerMethod    = (Action <Stream, int, SerializerObjectTracker>)GetTypeSerializer(typeof(int));

                WriteHeader(ms, cargo, options);

                if (!options.OmitRootTypeName)
                {
                    stringSerializerMethod(ms, SerializedTypeResolver.GetShortNameFromType(obj.GetType()), cargo);
                }

                intSerializerMethod(ms, SerializedTypeResolver.GetHashCodeFromType(obj.GetType()), cargo);
                serializerMethod(ms, objToSerialize, cargo);

                return(ms.ToArray());
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Clone an object
        /// </summary>
        /// <typeparam name="T">Any reference type</typeparam>
        /// <param name="obj">Object to clone</param>
        /// <returns>The cloned object</returns>
        public static T Clone <T>(T obj)
        {
            if (obj == null)
            {
                return(default(T));
            }

            object objToClone = ObjectCleaner.PrepareObjectForSerialization(obj);

            var refTracker = new ObjectClonerReferenceTracker();
            var clone      = CloneImpl(objToClone.GetType())(objToClone, refTracker);

            var queryable = IQueryableCloner.GetInterfaceType(obj.GetType(), typeof(IQueryable <>));

            if (queryable != null)
            {
                var genericArgumentType = queryable.GetGenericArguments()[0];
                return((T)Deserializer.ConvertObjectToIQueryable(clone, typeof(IQueryable <>).MakeGenericType(genericArgumentType)));
            }

            return((T)clone);
        }