本人觉得MemberwiseClone是不必要的 ,何必一定要用MemberwiseClone方法呢?你们说呢打个比方本人写一个程序你们看看:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace delete
{
public class Content
{
public int Val;
}
public class Cloner
{
public Content MyContent = new Content();
public Cloner(int newVal)
{
MyContent.Val = newVal;
}
}
class Program
{
static void Main(string[] args)
{
Cloner a = new Cloner(3);
Cloner b = a;//这里不一样也是浅度复制吗?何必一定要用MemberwiseClone方法呢
Console.WriteLine(b.MyContent.Val);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace delete
{
public class Content
{
public int Val;
}
public class Cloner
{
public Content MyContent = new Content();
public Cloner(int newVal)
{
MyContent.Val = newVal;
}
}
class Program
{
static void Main(string[] args)
{
Cloner a = new Cloner(3);
Cloner b = a;//这里不一样也是浅度复制吗?何必一定要用MemberwiseClone方法呢
Console.WriteLine(b.MyContent.Val);
}
}
}
解决方案
8
17
b = a;不是浅度复制,是引用拷贝。
namespace delete
{
public class Content
{
public int Val;
}
public class Cloner
{
public Content MyContent = new Content();
public Cloner(int newVal)
{
MyContent.Val = newVal;
}
public Cloner ShallowClone()
{
return (Cloner)this.MemberwiseClone();
}
}
class Program
{
static void Main(string[] args)
{
Cloner a = new Cloner(3);
Cloner b = a;//这里不是浅度复制。
Cloner c = a.ShallowClone();
// 区别1:
bool eq1 = object.ReferenceEquals(a, b); // true, a和b指向同一个对象。
bool eq2 = object.ReferenceEquals(a, c); // false, a和c是不同对象。
// 区别2:
b.MyContent = null; // 由于a和b是同一个对象,改变b的内容,等于改变a的内容
bool isnull1 = a.MyContent == null; // true
bool isnull2 = c.MyContent == null; // false,c的MyContent还在
}
}
}