标签:epc lang get att orm Matter ble 引用 回归
我们都知道memberwiseclone 会将浅克隆。
什么是浅克隆?如何深克隆呢?
public class good{
private good(){
oneclass=new class{
int id=8;
string name=‘id‘;
}
}
private static good __good;
private static good __good=new good();
public good createinstance()
{
return __good.memberwiseclone();
}
public int a=0;
public string b="ab";
pulic class oneclass;
}
测试:
void main()
{
var student1=good.createinstance();
var student2=good.createinstance();
student1.oneclass.id=9;
console.log(‘student2 oneclass.id{0}‘,student2.oneclass.id);
}
这里我们得出了结果为9;
ok,那么这真的是个匪夷所思的问题,明明两个对象啊。
那么回归到浅克隆上。
当克隆good的时候是这样的。
让good的classone的引用给了新的克隆对象。
那么如何深克隆呢?
深克隆其实就是将对象序列化,也就是说要深克隆的话必须对象系列化;
public class SerializeHelper
{
public static string Serializable(object target)
{
using (MemoryStream steam=new MemoryStream())
{
new BinaryFormatter().Serialize(steam,target);
return Convert.ToBase64String(steam.ToArray());
}
}
public static T Derializable<T>(string target)
{
byte[] targetArray = Convert.FromBase64String(target);
using (MemoryStream steam =new MemoryStream(targetArray))
{
return (T)(new BinaryFormatter().Deserialize(steam));
}
}
public static T DeepClone<T>(T t)
{
return Derializable<T>(Serializable(t));
}
}
改变一个good 类。
public class good{
private good(){
oneclass=new class{
int id=8;
string name=‘id‘;
}
}
private static good __good;
private static good __good=new good();
public good createinstance()
{
return SerializeHelper.DeepClone(__good.memberwiseclone());
}
public int a=0;
public string b="ab";
pulic class oneclass;
}
测试一下:
void main()
{
var student1=good.createinstance();
var student2=good.createinstance();
student1.oneclass.id=9;
console.log(‘student2 oneclass.id{0}‘,student2.oneclass.id);
}
标签:epc lang get att orm Matter ble 引用 回归
原文地址:https://www.cnblogs.com/aoximin/p/13195596.html