我有一个程序,我想根据一个值创建对象的新实例,然后取值,然后搜索列表,然后使用该列表创建新实例。
好吧,它进行得很好。但是有一个问题,我必须全部手动编写它们,并且要花很长时间。我想知道是否有更好的方法可以做到这一点,这是我拥有的C#代码
public Account (int userId) {
// here is look for the account
// inside a List<Account> which returns the account
// then I update the values for that instance,
this.AccountLockedSince = account.AccountLockedSince;
this.AuthenticationToken = account.AuthenticationToken;
this.CreateDate = account.CreateDate;
this.IsLocked = account.IsLocked;
this.IsVerified = account.IsVerified;
this.PasswordResetDate = account.PasswordResetDate;
this.PasswordResetToken = account.PasswordResetToken;
this.RequireEmailVerification = account.RequireEmailVerification;
this.TokenExpires = account.TokenExpires;
this.UserId = account.UserId;
}
..如您所见,这些都是Account类的所有属性,而我已经对其进行了更新,但这不是有效的方法。C#.NET框架中有任何内置功能可以处理此问题吗?
MemberwiseClone方法通过创建新对象,然后将当前对象的非静态字段复制到新对象来创建浅表副本。如果字段是值类型,则将执行该字段的逐位复制。如果字段是引用类型,则引用被复制,但引用的对象不是;否则,引用对象将被复制。因此,原始对象及其克隆引用相同的对象。
如果您需要深层副本,而不是浅层副本,请尝试使用序列化来创建深层副本。
您还可以使用Reflection获取和设置属性。请参见使用反射进行深拷贝。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句