111,129
社区成员
发帖
与我相关
我的任务
分享
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还在
}
}
}
但是你有没有想过,如果一个类不是1个字段,而是100个呢?不是要写到手抽筋了么