如何按值复制对象,而不是通过引用复制对象 [英] How to copy an object by value, not by reference

查看:124
本文介绍了如何按值复制对象,而不是通过引用复制对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想制作一个对象的副本,然后在一些逻辑之后,重新为原始对象分配副本的值。

I want to make a copy of an object, then after some logic, re-assign the original object the value of the copy.

例如:

User userCopy = //make a copy

foreach(...)
{
  user.Age = 1;
  user.ID = -1;

  UserDao.Update(user)


  user = userCopy; 

}

我不希望通过引用副本,它有按价值复制。

I don't want a copy by reference, it has to be a copy by value.

以上只是一个示例,而不是我真正想要如何使用它,但我需要学习如何按值复制。

The above is just a sample, not how I really want to use it but I need to learn how to copy by value.

推荐答案

以下是我听过的几种技巧:

Here are the few techniques I've heard of:


  1. 如果类实现 Cloneable ,请使用 clone()。这个API在java中有点缺陷,我从未完全理解为什么 clone 未在接口中定义,而是在 Object 。不过,它可能会有效。

  1. Use clone() if the class implements Cloneable. This API is a bit flawed in java and I never quite understood why clone is not defined in the interface, but in Object. Still, it might work.

手动创建克隆。如果有一个接受所有参数的构造函数,它可能很简单,例如 new User(user.ID,user.Age,...)。你甚至可能想要一个带有User的构造函数: new User(anotherUser)。

Create a clone manually. If there is a constructor that accepts all parameters, it might be simple, e.g new User( user.ID, user.Age, ... ). You might even want a constructor that takes a User: new User( anotherUser ).

实现一些东西从/向用户复制。该类可能有一个方法 copy(User),而不是使用构造函数。然后,您可以首先快照对象 backupUser.copy(用户),然后将其还原 user.copy(backupUser)。您可能有一个变体,其方法名为 backup / restore / snapshot

Implement something to copy from/to a user. Instead of using a constructor, the class may have a method copy( User ). You can then first snapshot the object backupUser.copy( user ) and then restore it user.copy( backupUser ). You might have a variant with methods named backup/restore/snapshot.

使用州模式

使用序列化。如果您的对象是图形,则可能更容易序列化/反序列化它以获得克隆。

Use serialization. If your object is a graph, it might be easier to serialize/deserialize it to get a clone.

全部取决于用例。选择最简单的。

That all depends on the use case. Go for the simplest.

编辑

我还建议看看在这些问题上:

I also recommend to have a look at these questions:

  • Clone() vs. Copy constructor
  • How to properly override clone method

这篇关于如何按值复制对象,而不是通过引用复制对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆