如何按值复制对象,而不是通过引用复制对象

编程入门 行业动态 更新时间:2024-10-27 04:25:49
本文介绍了如何按值复制对象,而不是通过引用复制对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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:

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

  • 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
  • 更多推荐

    如何按值复制对象,而不是通过引用复制对象

    本文发布于:2023-11-08 13:24:09,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1569487.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:对象   而不是

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!