Skip to content

Instantly share code, notes, and snippets.

@rqx110
Created September 6, 2018 01:37
Show Gist options
  • Save rqx110/a344569cf60c5160fc1f6b7d9c32ccd4 to your computer and use it in GitHub Desktop.
Save rqx110/a344569cf60c5160fc1f6b7d9c32ccd4 to your computer and use it in GitHub Desktop.
对象deep copy, 注意对象必须添加[Serializable]
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
namespace Abp.Extensions
{
public static class ObjectExtensions
{
public static T Dereference<T>(this object obj)
{
var formatter = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.Clone));
object oVal;
using (var stream = new MemoryStream())
{
formatter.Serialize(stream, obj);
stream.Position = 0;
oVal = formatter.Deserialize(stream);
stream.Flush();
stream.Close();
}
var result = (T)Convert.ChangeType(oVal, obj.GetType());
return result;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment