码迷,mamicode.com
首页 > Windows程序 > 详细

C# .Net 5 中 Serialize 已过时 BinaryFormatter.Serialize(Stream, object)”已过时

时间:2021-02-27 13:01:13      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:name   memory   returns   ros   using   default   反序列化   data   soft   

https://www.cnblogs.com/wangbg/p/14020022.html

https://docs.microsoft.com/zh-cn/dotnet/api/system.runtime.serialization.datacontractserializer?view=net-5.0

 /// <summary>
        /// 序列化
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private static byte[] Serialize(object obj)
        {
            if (obj == null)
                return null;

            using var memoryStream = new MemoryStream();
            DataContractSerializer ser = new DataContractSerializer(typeof(object));
            ser.WriteObject(memoryStream, obj);
            var data = memoryStream.ToArray();
            return data;
        }

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="data"></param>
        /// <returns></returns>
        private static T Deserialize<T>(byte[] data)
        {
            if (data == null)
                return default(T);

            using var memoryStream = new MemoryStream(data);
            XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(memoryStream, new XmlDictionaryReaderQuotas());
            DataContractSerializer ser = new DataContractSerializer(typeof(T));
            var result = (T)ser.ReadObject(reader, true);
            return result;
        }

C# .Net 5 中 Serialize 已过时 BinaryFormatter.Serialize(Stream, object)”已过时

标签:name   memory   returns   ros   using   default   反序列化   data   soft   

原文地址:https://www.cnblogs.com/LuoEast/p/14452227.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!