精华内容
下载资源
问答
  • 主要介绍了C#自定义序列化ISerializable的实现方法,涉及C#序列化的操作技巧,非常具有实用价值,需要的朋友可以参考下
  • c# custom serialization 自定义序列化两种方法:1、继承ISerializable,IDeserializationCallback 2、XML方式。(转) 自用
  • 将开发过程中经常用的内容段收藏起来,如下的资料是关于C#自定义序列化 ISerializable 的实现的内容,希望对小伙伴有些帮助。 [Serializable] public class BaseObject { [OptionalField] private string _str ...

    将开发过程中经常用的内容段收藏起来,如下的资料是关于C#自定义序列化 ISerializable 的实现的内容,希望对小伙伴有些帮助。

       [Serializable]
        public class BaseObject
        {
            [OptionalField]
            private string _str = "I am BaseObject";
        }
    
        [Serializable]
        public class TestObject : BaseObject, ISerializable
        {
            int a;
    
            string strName = "";
    
            Color c = Color.Red;
    
            DataTable _dtColors = null;
            [OptionalField]
            ArrayList list = new ArrayList();
    
            [OptionalField]
            List<int> list1 = new List<int>();
    
            [OptionalField]
            Dictionary<int, string> dic = new Dictionary<int, string>();
    
    
            [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)]
            protected TestObject(SerializationInfo info, StreamingContext context)
            {
                #region  如果基类也实现了ISerializable接口,则序列化器会自动调用基类的该构造函数,就不需要本段代码
                Type basetype = this.GetType().BaseType;
                MemberInfo[] mi = FormatterServices.GetSerializableMembers(basetype, context);
    
                for (int i = 0; i < mi.Length; i++)
                {
                    FieldInfo fi = (FieldInfo)mi[0];
                    object objValue = info.GetValue(basetype.FullName + "+" + fi.Name, fi.FieldType);
                    fi.SetValue(this, objValue);
                }
    
                #endregion
                a = info.GetInt32("a");
                strName = info.GetString("strName");
                c = (Color)info.GetValue("c", typeof(Color));
                _dtColors = (DataTable)info.GetValue("_dtColors", typeof(DataTable));
                list = (ArrayList)info.GetValue("list", typeof(ArrayList));
                list1 = (List<int>)info.GetValue("list1", typeof(List<int>));
                dic = (Dictionary<int, string>)info.GetValue("dic", typeof(Dictionary<int, string>));
            }
    
            public TestObject()
            {
                a = 100;
                strName = "daps";
                InitColorTable();
                list1.Add(10);
               list1.Add(20);       
            }
            #region ISerializable 成员
    
            [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter =true)]
            void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
            {
                info.AddValue("a", a);
                info.AddValue("strName", strName);
                info.AddValue("c", c);
                info.AddValue("_dtColors", _dtColors);
                info.AddValue("list", list);
                info.AddValue("list1", list1);
                info.AddValue("dic", dic);
                Type basetype = this.GetType().BaseType;
                MemberInfo[] mi = FormatterServices.GetSerializableMembers(basetype, context);
    
                for (int i = 0; i < mi.Length; i++)
                {
                    info.AddValue(basetype.FullName + "+" + mi[i].Name, ((FieldInfo)mi[i]).GetValue(this));
                }
            }
            #endregion
        }
    
    展开全文
  • c# 自定义序列化

    千次阅读 2018-10-19 16:44:16
    一、定义一个序列化的类(包含二进制,xml,json 三种方法)   public class SerializeHelper { #region 私有的 #region 字段 #endregion #region 方法 #endregion #endregion ...

     一、定义一个序列化的类(包含二进制,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);
                }

    展开全文
  • C# 自定义序列化问题

    2019-10-06 22:01:58
    C# 自定义序列化问题 public class overdue { public int overdueTimes { get; set; } /// <summary> /// 90天以上逾期次...
        public class overdue
        {
            public int overdueTimes { get; set; }
            /// <summary>
            /// 90天以上逾期次数
            /// </summary>
            [JsonProperty(PropertyName = "90overdueTimes")]
            public int overdueTimes90 { get; set; }
            /// <summary>
            /// 180天以上逾期次数
            /// </summary>
            [JsonProperty(PropertyName = "180overdueTimes")]
            public int overdueTimes180 { get; set; }
        }
    posted on 2016-06-08 14:44  笨小孩做开发 阅读( ...) 评论( ...) 编辑 收藏

    转载于:https://www.cnblogs.com/dullbaby/p/5570047.html

    展开全文
  • MSDN注解:允许对象控制其自己的序列化和反序列化过程。 ISerializable 接口的定义: public interface ISerializable { void GetObjectData(SerializationInfo info, StreamingContext context); } 意思...

    ISerializable 接口

    MSDN注解:允许对象控制其自己的序列化和反序列化过程。

    ISerializable 接口的定义:

    public interface ISerializable
    {
        void GetObjectData(SerializationInfo info, StreamingContext context);
    }

    意思就是我们可以通过实现 ISerializable 接口来控制序列化与反序列化后的结果。但是只有使用 BinaryFormatter 时才有用。使用 JavaScriptSerializer 类并没有效果。下面通过一个示例学习一下。

    示例

    定义实现 ISerializable 接口的类:

    [Serializable]  //记得标记此 Attribute
    public class Product : ISerializable
    {
        private string _name;
        public Product() { }
    
        public Product(SerializationInfo info, StreamingContext context)
        {
            _name = (String)info.GetValue("Name", typeof(String));
        }
    
        public String Name
        {
            get { return this._name; }
            set { this._name = value; }
        }
    
        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue("Name", "JRoger.NET",typeof(String));
        }
    }

     通过 BinaryFormatter 序列化和反序列化此类:

    [Test]
    public void SerializableTest()
    {
        var product = new Product { Name = "Hello" };
        var formatter = new BinaryFormatter();
        var stream = File.Open(@"E:\Log.bin", FileMode.OpenOrCreate, FileAccess.ReadWrite);
    
        formatter.Serialize(stream, product);
    
        stream.Close();
        stream.Dispose();
    
        var obj = (Product)formatter.Deserialize(File.Open(@"E:\Log.bin", FileMode.OpenOrCreate, FileAccess.ReadWrite));
    
        Trace.WriteLine(obj.Name);
    }

     可以看到,实例化 Product 类时,Name 属性的值为 "Hello" 而反序列化后输出结果却为 "JRoger.NET"。其实控制序列化和反序列化结果的关键就是实现 ISerializable 接口。另外实现 ISerializable 接口的类还要有一个带有两个参数的构造函数,这两个参数的类型分别为: SerializationInfoStreamingContext 。

    总结

    总的来说实现上很简单,配上示例也很容易。但是使用自定义序列化和反序列化的场景可能并不多。不过作为学习内容还是很有必要的。使用场景少,并不代表没有。不要放过任何细节。

    展开全文
  • C#基础知识梳理系列十四:序列 C#编程总结(一)序列化 Xml序列化
  • C#自定义序列化的Dictionary类型
  • 在我们深入探讨C#序列化和反序列化之前我们先要明白什么是序列化,它又称串行化,是.NET运行时环境用来支持用户定义类型的流化的机制。序列化就是把一个对象保存到一个文件或数据库字段中去,反序列化就是在适当的...
  • 本文实例讲述了C#序列化到类的实现方法。分享给大家供大家参考。具体实现方法如下: using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization.Formatters....
  • C# JavaScriptSerializer 自定义序列化

    热门讨论 2019-11-01 10:22:49
    虽然,我个人建议使用Json.Net。 但大家需求不同。遇到一个朋友,他有个需求...这里我采用自定义序列化来实现: public static void Main(string[] args) { MyException my = new MyException(); ...
  • 在没有默认构造函数的情况下使用Custom Serializer或Substitute Pattern序列化类型会更好吗? 将FontFamily序列化为WP7中的隔离存储的示例。
  • 相信大家在工作中会经常遇见对json进行序列化与反序列化吧,但通常的序列化与反序列化中的json结构与c#中的类模型结构是相对应的,我们是否可以在序列化一个对象时候,让我们json的数据结构能按照自己的意愿,而不必...
  • 通过序列化对象的方式实现的自定义工程文件功能。 一、涉及技术: 1.序列化:通过对象序列化,保存对象ProClass的两个属性到二进制文件中,然后再通过反序列化把保存2.的两个属性读出来。 窗体间变量的值传递:将...
  • #region 成员变量序列化(转化为string、从string赋值) /// /// 获取Object对象,所有成员变量信息 /// public static string getAllFields(Object obj) { string data = "\r\n"; FieldInfo[] fields = ...
  • Newtonsoft.Json 自定义序列化字段

    千次阅读 2019-07-01 15:49:54
    class Program { static void Main(string[] args) { var m = new JsonModel() { Id = 0, Name = "nnnn" }; ...
  • 获取元数据的介绍,从类名获取、从实例中获取,从类的镜像文件中获取,序列化与反序列化 数据模型
  • 用于实体框架代码优先C#自定义种子序列化
  • 最近在java中使用protobuf,每次序列化序列化都需要知道具体的Pb对象然后在调用其build().toByteArray()和parseFrom()。然框架使用的是动态代理来反射调用逻辑处理类,也就是需要动态的获取参数对象才能对其序列化...
  • 通过一个简单的序列化序列化方法,其中有自定义事件,窗口传递参数,共享对象等知识
  • C#中二进制数组h和各种常规数组的转换,二进制序列化和json序列化方法以及对应的反序列化方法的例子,帮助初学者。
  • 新建控制台console项目,添加XmlPersonIXmlSerializable类,和AddressIXmlSerializable类(实现IXmlSerializable... Console.WriteLine($"测试序列化结果:\r\n{s}"); Console.ReadLine(); } } } 运行结果:
  • 通过Linq To JSON可以快速的读写Json,通过JsonSerializer可以序列化你的.Net对象。 让你轻松实现.Net中所有类型(对象,基本数据类型等)和Json的转换. 官网上三种不同的组件性能对比 /*********************...
  • Newtonsoft.Json 自定义序列化特性

    千次阅读 2016-04-04 22:21:45
    目前在项目中经常使用Newtonsoft.Json,因项目需要对其中的特定数据类型序列化有特殊要求,特地学习了下如何对Newtonsoft.Json的序列化进行自定义扩展开发。 1、对DateTime类型,序列化输出为时间戳; 2、对string...
  • c#中如何实现一个类的序列化,以及把自己的数据保存到自定义的文件类型当中
  • C#C#中实现序列化

    2020-06-16 01:35:06
    序列化使用到了C#中的BinaryFormatter 类。 首先我有一个Fighting类,里面有一个FightingConfigure类的实例。并且还有一个FightingConfigure类。结构如下 public class Fighting { public FightingConfigure ...
  • 序列化协议与自定义序列化协议 序列化定义 序列化(serialization)就是将对象序列化为二进制形式(字节数组),一般也将序列化称为编码(Encode),主要用于网络传输、数据持久化等; 反序列化...
  • C#序列化和反序列化自定义的类对象是比较容易的,比如像下面的一个Customer类, private class Customer { public string CustomerName { get; set; } public string Email { get; set; } public int Age { ...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 26,419
精华内容 10,567
关键字:

c#自定义序列化

c# 订阅