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

问题描述

可能重复:结果
  How你做一个深拷贝的对象在.net中(特别是C#)?

请看看下面(摘自一个C#的书)在code:

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

namespace Example
{
    class MyClass
    {
        public int val;
    }
    struct myStruct
    {
        public int val;
    }
    class Program
    {
        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
objectA.val = 20
structB.val = 30
structB.val = 40

输出我有没有问题,但前两个的最后两行告诉我,对象A 对象B 都指向了同一个内存块(因为在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).

现在的问题是如何让对象B 对象A 的副本,以便它指向一个不同的区域记忆。据我所知,想他们的成员分配可能无法正常工作,因为这些成员可能是引用了。那么,如何去让对象B 对象A 一个完全不同的实体?

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 接口(但它是那种德precated),或者只写你自己的复制/ Clone方法。在这两种情况下,你必须写一些code。

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),只是为了重新使用现有的code。

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

不管是什么方法,仔细思考什么是复制的意思完全相同。它应该有多深,是否有标识字段的除外等。

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#中的副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 20:52