在 C# 中创建对象的副本 [英] Creating a copy of an object in C#

查看:47
本文介绍了在 C# 中创建对象的副本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请看下面的代码(摘自一本 C# 书籍):

Please have a look at the code below (excerpt from a C# book):

public class MyClass 
{
    public int val;
}
public struct myStruct 
{
    public int val;
}
public class Program 
{
    private static void Main(string[] args) 
    {
        MyClass objectA = new MyClass();
        MyClass objectB = objectA;

        objectA.val = 10;
        objectB.val = 20;

        myStruct structA = new myStruct();
        myStruct structB = structA;

        structA.val = 30;
        structB.val = 40;

        Console.WriteLine("objectA.val = {0}", objectA.val);
        Console.WriteLine("objectB.val = {0}", objectB.val);
        Console.WriteLine("structA.val = {0}", structA.val);
        Console.WriteLine("structB.val = {0}", structB.val);

        Console.ReadKey();
    }
}

我知道它会产生以下输出:

I understands it produces the output below:

objectA.val = 20
objectB.val = 20
structA.val = 30
structB.val = 40

输出的最后两行我没有问题,但前两行告诉我 objectAobjectB 指向同一个内存块(因为在C#,对象是引用类型).

The last two lines of the output I have no problem with, but the first two tell me that objectA and objectB are pointing to the same memory block (since in C#, objects are reference types).

问题是如何制作objectB,一个objectA 的副本,以便它指向内存中的不同区域.我知道尝试分配他们的成员可能不起作用,因为这些成员也可能是参考.那么我如何让 objectB 成为一个与 objectA 完全不同的实体?

The question is how do make objectB, a copy of objectA so that it points to a different area in memory. I understand that trying to assign their members may not work since those members may be references, too. So how do I go about making objectB a completely different entity from objectA?

推荐答案

没有内置的方式.您可以让 MyClass 实现 IClonable 接口(但它有点过时)或只编写您自己的 Copy/Clone 方法.无论哪种情况,您都必须编写一些代码.

There is no built-in way. You can have MyClass implement the IClonable interface (but it is sort of deprecated) or just write your own Copy/Clone method. In either case you will have to write some code.

对于大对象,您可以考虑序列化 + 反序列化(通过 MemoryStream),只是为了重用现有代码.

For big objects you could consider Serialization + Deserialization (through a MemoryStream), just to reuse existing code.

无论采用何种方法,请仔细考虑副本"的确切含义.它应该走多深,是否有要排除的Id字段等.

Whatever the method, think carefully about what "a copy" means exactly. How deep should it go, are there Id fields to be excepted etc.

这篇关于在 C# 中创建对象的副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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