Created
September 6, 2018 01:37
-
-
Save rqx110/a344569cf60c5160fc1f6b7d9c32ccd4 to your computer and use it in GitHub Desktop.
对象deep copy, 注意对象必须添加[Serializable]
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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