gpt4 book ai didi

c# - 克隆对象的好方法

转载 作者:太空宇宙 更新时间:2023-11-03 17:02:08 25 4
gpt4 key购买 nike

<分区>

我必须克隆一些实体,然后我写了这段代码。

public override object Clone()
{
var CloneUser = base.Clone() as FMSUser;

CloneUser.Username = this.Username;
CloneUser.IsEnabled = this.IsEnabled;
CloneUser.IsNeedPasswordReset = this.IsNeedPasswordReset;
CloneUser.LastName = this.LastName;
CloneUser.FirstName = this.FirstName;
CloneUser.MiddleName = this.MiddleName;
CloneUser.DistributorID = this.DistributorID;
CloneUser.IsLocked = this.IsLocked;

return CloneUser;
}

但后来我的同事给我发了这段代码,说这样克隆更好,但不能告诉我为什么:

public FMSUser(FMSUser user)
{
this.Username = user.Username;
this.IsEnabled = user.IsEnabled;
this.IsNeedPasswordReset = user.IsNeedPasswordReset;
this.LastName = user.LastName;
this.FirstName = user.FirstName;
this.MiddleName = user.MiddleName;
this.DistributorID = user.DistributorID;
this.IsLocked = user.IsLocked;
}
public override object Clone()
{
return new FMSUser(this);
}

谁能解释为什么第二种方法更好?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com