| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 |
- using System;
- using System.IO;
- using System.Runtime.Serialization.Formatters.Binary;
- using IwbZero.ToolCommon.LogHelpers;
- namespace IwbZero.ToolCommon.StringModel
- {
- public static class SerializeHelper
- {
- /// <summary>
- /// 深拷贝(对象需有[Serializable]可序列化特性)
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="target"></param>
- /// <returns></returns>
- public static T DeepClone<T>(this T target)
- {
- return IwbDerializable<T>(IwbSerializable(target));
- }
- public static string IwbSerializable(object target)
- {
- try
- {
- using (MemoryStream stream = new MemoryStream())
- {
- new BinaryFormatter().Serialize(stream, target);
- return Convert.ToBase64String(stream.ToArray());
- }
- }
- catch (Exception e)
- {
- typeof(SerializeHelper).LogError(e);
- return null;
- }
- }
- public static T IwbDerializable<T>(string target)
- {
- try
- {
- byte[] targetArray = Convert.FromBase64String(target);
- using (MemoryStream stream = new MemoryStream(targetArray))
- {
- return (T)new BinaryFormatter().Deserialize(stream);
- }
- }
- catch (Exception e)
- {
- typeof(SerializeHelper).LogError(e);
- return default(T);
- }
- }
- }
- }
|