c# 自定义可序列化

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_23338865/article/details/83184583

 一、定义一个序列化的类(包含二进制,xml,json 三种方法)

    public class SerializeHelper
    {
        #region 私有的
        #region 字段
        #endregion
        #region 方法
        #endregion
        #endregion
        #region 保护的
        #region 字段

        #endregion
        #region 方法
        #endregion
        #endregion
        #region 公开的

        #region 属性

        #endregion
        #region 方法

        #endregion
        #endregion

        #region 静态方法
        #region 二进制方式
        /// <summary>
        /// 序列化对像
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="FileName"></param>123456
        /// <param name="Exception">是否显示异常消息</param>
        /// <returns></returns>
        public static bool Serialize(object obj, string FileName, bool showException)
        {
            FileInfo fi = new FileInfo(FileName);
            if (!fi.Directory.Exists) fi.Directory.Create();
            using (FileStream fileStream = new FileStream(FileName, FileMode.Create))
            {
                try
                {
                    BinaryFormatter b = new BinaryFormatter();
                    b.Serialize(fileStream, obj);
                    return true;
                }
                catch (Exception ex)
                {
                    if (showException)
                    {
                        throw new Exception(ex.Message);
                    }
                    return false;
                }
            }
        }

        /// <summary>
        /// 序列化对像
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="FileName"></param>123456
        /// <param name="Exception">是否显示异常消息</param>
        /// <returns></returns>
        public static byte[] Serialize(object obj,bool showException)
        {
            using (MemoryStream fileStream = new MemoryStream())
            {
                try
                {
                    BinaryFormatter b = new BinaryFormatter();
                    b.Serialize(fileStream, obj);
                    return fileStream.ToArray();
                }
                catch (Exception ex)
                {
                    if (showException)
                    {
                        throw new Exception(ex.Message);
                    }
                    return null;
                }
            }
        }

        /// <summary>
        /// 反序列化对像
        /// </summary>
        /// <param name="FileName"></param>
        /// <param name="showException">是否显示异常消息</param>
        /// <returns></returns>
        public static object DeSerialize(string FileName, bool showException)
        {
           return DeSerialize(FileName, showException);
        }

        /// <summary>
        /// 反序列化对像
        /// </summary>
        /// <param name="FileName"></param>
        /// <param name="showException">是否显示异常消息</param>
        /// <returns></returns>
        public static object DeSerialize(byte[] inputBuf, bool showException)
        {
            return DeSerialize<object>(inputBuf, showException);
        }

        /// <summary>
        ///  反序列化对像
        /// </summary>
        /// <typeparam name="T">返回的类型</typeparam>
        /// <param name="FileName"></param>
        /// <param name="showException">是否显示异常消息</param>
        /// <returns></returns>
        public static T DeSerialize<T>(string FileName, bool showException)
        {
            if (!System.IO.File.Exists(FileName))
            {
                if (showException) throw new Exception("文件不存");
                return default(T);
            }
            using (FileStream fileStream = new FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                try
                {
                    BinaryFormatter b = new BinaryFormatter();
                    b.Binder = new ObjBinderEx<T>();
                    object obj = b.Deserialize(fileStream);
                    return (T)obj;
                }
                catch (Exception ex)
                {
                    if (showException)
                    {
                        throw new Exception(ex.Message);
                    }
                    return default(T);

                }
            }
        }
        /// <summary>
        ///  反序列化对像
        /// </summary>
        /// <typeparam name="T">返回的类型</typeparam>
        /// <param name="FileName"></param>
        /// <param name="showException">是否显示异常消息</param>
        /// <returns></returns>
        public static T DeSerialize<T>(byte[] inputBuf, bool showException)
        {

            using (MemoryStream fileStream = new MemoryStream(inputBuf))
            {
                try
                {
                    BinaryFormatter b = new BinaryFormatter();
                    b.Binder = new ObjBinderEx<T>();
                    object obj = b.Deserialize(fileStream);

                    return (T)obj;
                }
                catch (Exception ex)
                {
                    if (showException)
                    {
                        throw new Exception(ex.Message);
                    }
                    return default(T);

                }
            }
        }
        #endregion
        #region XML方式
        /// <summary>
        /// 序列化对像
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="FileName"></param>
        /// <param name="Exception">是否显示异常消息</param>
        /// <returns></returns>
        public static bool XMLSerialize(object obj, string FileName, bool showException)
        {
            FileInfo fi = new FileInfo(FileName);
            if (!fi.Directory.Exists) fi.Directory.Create();
            using (FileStream fileStream = new FileStream(FileName, FileMode.Create))
            {
                try
                {
                    XmlSerializer b = new XmlSerializer(obj.GetType());
                    b.Serialize(fileStream, obj);
                    return true;
                }
                catch (Exception ex)
                {
                    if (showException)
                    {
                        throw new Exception(ex.Message);
                    }
                    return false;
                }
            }
        }

        /// <summary>
        /// 序列化对像
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="FileName"></param>
        /// <param name="Exception">是否显示异常消息</param>
        /// <returns></returns>
        public static byte[] XMLSerialize(object obj, bool showException)
        {
            using (MemoryStream fileStream = new MemoryStream())
            {
                try
                {
                    XmlSerializer b = new XmlSerializer(obj.GetType());
                    b.Serialize(fileStream, obj);
                    return fileStream.ToArray() ;
                }
                catch (Exception ex)
                {
                    if (showException)
                    {
                        throw new Exception(ex.Message);
                    }
                    return null;
                }
            }
        }

        /// <summary>
        /// 反序列化对像
        /// </summary>
        /// <param name="FileName"></param>
        /// <param name="showException">是否显示异常消息</param>
        /// <typeparam name="T">返回对像的类型</typeparam>
        /// <returns></returns>
        public static T XMLDeSerialize<T>(string FileName, bool showException)
        {
            if (!System.IO.File.Exists(FileName))
            {
                if (showException) throw new Exception("文件不存");
                return default(T);
            }
            using (FileStream fileStream = new FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                try
                {
                    XmlSerializer b = new XmlSerializer(typeof(T));
                   
                    T obj = (T)b.Deserialize(fileStream);
                    return obj;
                }
                catch (Exception ex)
                {
                    if (showException)
                    {
                        throw new Exception(ex.Message);
                    }
                    return default(T);

                }
            }
        }

        /// <summary>
        /// 反序列化对像
        /// </summary>
        /// <param name="FileName"></param>
        /// <param name="showException">是否显示异常消息</param>
        /// <typeparam name="T">返回对像的类型</typeparam>
        /// <returns></returns>
        public static T XMLDeSerialize<T>(byte[] inputBuf, bool showException)
        {
            using (MemoryStream fileStream = new MemoryStream(inputBuf))
            {
                try
                {
                    XmlSerializer b = new XmlSerializer(typeof(T));
                    T obj = (T)b.Deserialize(fileStream);
                    return obj;
                }
                catch (Exception ex)
                {
                    if (showException)
                    {
                        throw new Exception(ex.Message);
                    }
                    return default(T);

                }
            }
        }

        #endregion
        #region Json方式
        public static string ToJson(object obj,bool showException)
        {
            try
            {
                return Newtonsoft.Json.JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.Indented);
            }
            catch (Exception ex)
            {
                if (showException)
                {
                    throw new Exception(ex.Message);
                }
                return null;
            }
        }
        /// <summary>
        /// 序列化对像
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="FileName"></param>
        /// <param name="Exception">是否显示异常消息</param>
        /// <returns></returns>
        public static bool JsonSerialize(object obj, string FileName, bool showException)
        {
            FileInfo fi = new FileInfo(FileName);
            if (!fi.Directory.Exists) fi.Directory.Create();
            try
            {
              
                var jsonStr = Newtonsoft.Json.JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.Indented);
                File.WriteAllText(FileName, jsonStr, Encoding.UTF8);
                return true;
            }
            catch (Exception ex)
            {
                if (showException)
                {
                    throw new Exception(ex.Message);
                }
                return false;
            }

        }

        /// <summary>
        /// 反序列化对像
        /// </summary>
        /// <param name="FileName"></param>
        /// <param name="showException">是否显示异常消息</param>
        /// <typeparam name="T">返回对像的类型</typeparam>
        /// <returns></returns>
        public static T JsonDeSerialize<T>(string FileName, bool showException)
        {
            if (!System.IO.File.Exists(FileName))
            {
                if (showException) throw new Exception("文件不存");
                return default(T);
            }
            try
            {
                var jsonStr = File.ReadAllText(FileName, Encoding.UTF8);
                var obj = JsonConvert.DeserializeObject<T>(jsonStr);
                return obj;
            }
            catch (Exception ex)
            {
                if (showException)
                {
                    throw new Exception(ex.Message);
                }
                return default(T);

            }

        }

        /// <summary>
        /// 反序列化对像
        /// </summary>
        /// <param name="FileName"></param>
        /// <param name="showException">是否显示异常消息</param>
        /// <typeparam name="T">返回对像的类型</typeparam>
        /// <returns></returns>
        public static T FromJson<T>(string jsonStr, bool showException)
        {
            if (!string.IsNullOrEmpty(jsonStr))
            {
                if (showException) throw new Exception("空字符串");
                return default(T);
            }
            try
            {
                var obj = JsonConvert.DeserializeObject<T>(jsonStr);
                return obj;
            }
            catch (Exception ex)
            {
                if (showException)
                {
                    throw new Exception(ex.Message);
                }
                return default(T);

            }

        }
        #endregion
        /// <summary>
        /// 将对像的属性序列化到本地
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="filename"></param>
        /// <returns></returns>
        public static bool SerializePropertys(object obj, string FileName)
        {
            FileInfo fi = new FileInfo(FileName);
            if (!fi.Directory.Exists) fi.Directory.Create();
            PropertyInfo[] pis = obj.GetType().GetProperties();
            SerializeHash dict = new SerializeHash();
            foreach (PropertyInfo pi in pis)
            {
                if (!pi.CanWrite) continue;
                if (pi.GetIndexParameters().Length > 0) continue;
                Type t = pi.PropertyType;

                if ((t == typeof(string)) || (t == typeof(int)) || (t == typeof(short)) || (t == typeof(decimal)) || (t == typeof(double)) || (t == typeof(float)) || (t == typeof(byte)) || (t == typeof(bool))
                    || (t == typeof(DateTime)) || (t == typeof(DateTime?)) || (t.IsEnum) || (t == typeof(long))||(t == typeof(Image)))
                {
                    dict.Add(pi.Name, pi.GetValue(obj, null));
                }
            }
            return dict.SaveToFile(FileName, false);
          //  return true;
        }
        /// <summary>
        /// 从本地载入对像的属性
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="filename"></param>
        /// <returns></returns>
        public static bool DeSerializePropertys(object obj, string filename)
        {
            SerializeHash dict = SerializeHash.CreateFromFile(filename, false);
            if (dict == null) return false;
            PropertyInfo[] pis = obj.GetType().GetProperties();
            foreach (PropertyInfo pi in pis)
            {
                if (!pi.CanWrite) continue;
                if (pi.GetIndexParameters().Length > 0) continue;
                if (dict.ContainsKey(pi.Name))
                {
                    try
                    {
                        pi.SetValue(obj, dict[pi.Name], null);
                    }
                    catch
                    {
                    }
                }
            }
            return true;
        }
        #endregion
    }

二、定义一个可序列话字典类

/// <summary>
/// 可序列化的字典类,要求包含对像也可序列化
/// </summary>
/// <typeparam name="TKey"></typeparam>
/// <typeparam name="TValue"></typeparam>
   [Serializable()]
	public class SerializableDictionary<TKey, TVal> : Dictionary<TKey, TVal>, IXmlSerializable, ISerializable
	{
		#region Constants
		private const string DictionaryNodeName = "Dictionary";
		private const string ItemNodeName = "Item";
		private const string KeyNodeName = "Key";
		private const string ValueNodeName = "Value";
		#endregion
		#region Constructors
		public SerializableDictionary()
		{
		}

		public SerializableDictionary(IDictionary<TKey, TVal> dictionary)
			: base(dictionary)
		{
		}

		public SerializableDictionary(IEqualityComparer<TKey> comparer)
			: base(comparer)
		{
		}

		public SerializableDictionary(int capacity)
			: base(capacity)
		{
		}

		public SerializableDictionary(IDictionary<TKey, TVal> dictionary, IEqualityComparer<TKey> comparer)
			: base(dictionary, comparer)
		{
		}

		public SerializableDictionary(int capacity, IEqualityComparer<TKey> comparer)
			: base(capacity, comparer)
		{
		}

		#endregion
		#region ISerializable Members

		protected SerializableDictionary(SerializationInfo info, StreamingContext context)
		{
			int itemCount = info.GetInt32("ItemCount");
			for (int i = 0; i < itemCount; i++)
			{
				KeyValuePair<TKey, TVal> kvp = (KeyValuePair<TKey, TVal>)info.GetValue(String.Format("Item{0}", i), typeof(KeyValuePair<TKey, TVal>));
				this.Add(kvp.Key, kvp.Value);
			}
		}

		void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
		{
			info.AddValue("ItemCount", this.Count);
			int itemIdx = 0;
			foreach (KeyValuePair<TKey, TVal> kvp in this)
			{
				info.AddValue(String.Format("Item{0}", itemIdx), kvp, typeof(KeyValuePair<TKey, TVal>));
				itemIdx++;
			}
		}

		#endregion
		#region IXmlSerializable Members

		void IXmlSerializable.WriteXml(System.Xml.XmlWriter writer)
		{
			//writer.WriteStartElement(DictionaryNodeName);
			foreach (KeyValuePair<TKey, TVal> kvp in this)
			{
				writer.WriteStartElement(ItemNodeName);
				writer.WriteStartElement(KeyNodeName);
				KeySerializer.Serialize(writer, kvp.Key);
				writer.WriteEndElement();
				writer.WriteStartElement(ValueNodeName);
				ValueSerializer.Serialize(writer, kvp.Value);
				writer.WriteEndElement();
				writer.WriteEndElement();
			}
			//writer.WriteEndElement();
		}

		void IXmlSerializable.ReadXml(System.Xml.XmlReader reader)
		{
			if (reader.IsEmptyElement)
			{
				return;
			}

			// Move past container
			if (!reader.Read())
			{
				throw new XmlException("Error in Deserialization of Dictionary");
			}

			//reader.ReadStartElement(DictionaryNodeName);
			while (reader.NodeType != XmlNodeType.EndElement)
			{
				reader.ReadStartElement(ItemNodeName);
				reader.ReadStartElement(KeyNodeName);
				TKey key = (TKey)KeySerializer.Deserialize(reader);
				reader.ReadEndElement();
				reader.ReadStartElement(ValueNodeName);
				TVal value = (TVal)ValueSerializer.Deserialize(reader);
				reader.ReadEndElement();
				reader.ReadEndElement();
				this.Add(key, value);
				reader.MoveToContent();
			}
			//reader.ReadEndElement();

			reader.ReadEndElement(); // Read End Element to close Read of containing node
		}

		System.Xml.Schema.XmlSchema IXmlSerializable.GetSchema()
		{
			return null;
		}

		#endregion
		#region Private Properties
		protected XmlSerializer ValueSerializer
		{
			get
			{
				if (valueSerializer == null)
				{
					valueSerializer = new XmlSerializer(typeof(TVal));
				}
				return valueSerializer;
			}
		}

		private XmlSerializer KeySerializer
		{
			get
			{
				if (keySerializer == null)
				{
					keySerializer = new XmlSerializer(typeof(TKey));
				}
				return keySerializer;
			}
		}
		#endregion
		#region Private Members
		private XmlSerializer keySerializer = null;
		private XmlSerializer valueSerializer = null;
		#endregion
        public bool SaveToFile(string FileName, bool showException)
        {
           return  SerializeHelper.XMLSerialize(this, FileName, showException);
        }

    }

三、定义可序列序列化实例类

   /// <summary>
    ///  可序列的哈希表,只能通过XML序列化
    /// </summary>
    [Serializable]
   public class SerializeHash : SerializableDictionary<string, object>
    {
        public SerializeHash()
            : base()
        {
        }
        public SerializeHash(IDictionary<string, object> dictionary)
            : base(dictionary)
        {
        }

        public SerializeHash(IEqualityComparer<string> comparer)
            : base(comparer)
        {
        }

        public SerializeHash(int capacity)
            : base(capacity)
        {
        }

        public SerializeHash(IDictionary<string, object> dictionary, IEqualityComparer<string> comparer)
            : base(dictionary, comparer)
        {
        }

        public SerializeHash(int capacity, IEqualityComparer<string> comparer)
            : base(capacity, comparer)
        {
        }

        protected SerializeHash(SerializationInfo info, StreamingContext context)
        {
            int itemCount = info.GetInt32("ItemCount");
            for (int i = 0; i < itemCount; i++)
            {
                KeyValuePair<string, object> kvp = (KeyValuePair<string, object>)info.GetValue(String.Format("Item{0}", i), typeof(KeyValuePair<string, object>));
                this.Add(kvp.Key, kvp.Value);
            }
        }


        /// <summary>
        /// 将内含数据转为对应的类型
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Name"></param>
        /// <param name="DefaultValue"></param>
        /// <returns></returns>
        public T GetObject<T>(string Name, T DefaultValue)
        {
            if (!this.ContainsKey(Name)) return DefaultValue;
            object obj = this[Name];
            if(!(obj is T)) return DefaultValue;
           return (T)obj;
        }

        public void SetObject(string Name, object Value)
        {
            if (this.ContainsKey(Name)) this[Name] = Value;
            else this.Add(Name, Value);
        }
        public static SerializeHash CreateFromFile(string FileName, bool showException)
        {
            return SerializeHelper.XMLDeSerialize<SerializeHash>(FileName, showException);
        }

        public bool SaveToFile(string FileName, bool showException)
        {
            return SerializeHelper.XMLSerialize(this, FileName, showException);
        }
    }

 四 使用实例:

private static SerializeHash mSystemCachData;

SystemCachData.SetObject("weburl", "www.baidu.com");

if (mSystemCachData != null)
            {
                mSystemCachData.SaveToFile(System.IO.Path.Combine(Path, "DefaultData.xml"), false);
            }

猜你喜欢

转载自blog.csdn.net/sinat_23338865/article/details/83184583