コード例 #1
0
        /// <summary>
        /// Serialize the object.
        /// </summary>
        /// <typeparam name="T">the Root type used for serialization</typeparam>
        public static string SerializeEx <T>(this T obj)
        {
            Type[]       t  = SerializableExtraTypes.GetTypes(typeof(T)).ToArray();
            var          x  = new XmlSerializer(typeof(T), t);
            StringWriter sw = new StringWriter();

            x.Serialize(sw, obj);
            return(sw.ToString());
        }
コード例 #2
0
        /// <summary>
        /// Serialize the object
        /// </summary>
        /// <param name="root">the Root type used for serialization</param>
        /// <returns></returns>
        public static string SerializeEx <T>(this T obj, params Type[] root)
        {
            Type[] t = (from y in root
                        select SerializableExtraTypes.GetTypes(y))
                       .Flatten()
                       .Union(SerializableExtraTypes.GetTypes(typeof(T)))
                       .Distinct()
                       .ToArray();
            var          x  = new XmlSerializer(typeof(T), t);
            StringWriter sw = new StringWriter();

            x.Serialize(sw, obj);
            return(sw.ToString());
        }
コード例 #3
0
        /// <summary>
        /// Deserialize the object to the given type.
        /// </summary>
        public static T DeserializeEx <T>(this string xml)
        {
            Type[]      t   = SerializableExtraTypes.GetTypes(typeof(T)).ToArray();
            var         x   = new XmlSerializer(typeof(T), t);
            XmlDocument doc = new XmlDocument();

            doc.LoadXml(xml);
            var r = XmlReader.Create(new StringReader(xml));

            if (!x.CanDeserialize(r))
            {
                throw new FormatException(string.Format("Unable to deserialize string into {0}, root node does not match.", typeof(T).FullName));
            }
            return((T)x.Deserialize(r));
        }