C#创建一个深度复制 [英] Create a Deep Copy in C#

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

问题描述

我想打一个对象的深层副本,以便我可以改变的新副本,还是要取消我的变化,回到原始对象的选项。

I want to make a deep copy of an object so I could change the the new copy and still have the option to cancel my changes and get back the original object.

这里我的问题是,对象可以是任何类型的,甚至从一个未知的组件。
我不能使用的BinaryFormatter 的XmlSerializer ,因为对象不必要有[Serializable]属性。

My problem here is that the object can be of any type, even from an unknown assembly. I can not use BinaryFormatter or XmlSerializer, because the object unnecessarily have [Serializable] attribute.

我试图做到这一点使用 Object.MemberwiseClone()方法:

I have tried to do this using the Object.MemberwiseClone() method:

public object DeepCopy(object obj)
{
    var memberwiseClone = typeof(object).GetMethod("MemberwiseClone", BindingFlags.Instance | BindingFlags.NonPublic);

    var newCopy = memberwiseClone.Invoke(obj, new object[0]);

    foreach (var field in newCopy.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
    {
        if (!field.FieldType.IsPrimitive && field.FieldType != typeof(string))
        {
            var fieldCopy = DeepCopy(field.GetValue(newCopy));
            field.SetValue(newCopy, fieldCopy);
        }
    }
    return newCopy;
}

在这里的问题是,它不是工作的一个枚举(数组,列表等),而不是字典。

The problem in this is that it's not working on an enumerable (array, list etc.), an not on dictionary.

那么,怎样才能让我不明物体的深层副本在C#?

So, how can I make a deep copy of an unknown object in C#?

TNX很多!

推荐答案

这是完全不可能的深复制任意对象。

It is completely impossible to deep-copy an arbitrary object.

例如,你会怎么处理控制的FileStream HttpWebResponse

For example, how would you handle a Control or a FileStream or an HttpWebResponse?

您code无法知道它的字段对象如何工作,哪些应该包含

Your code cannot know how the object works and what its fields are supposed to contain.

不要这样做。结果
这是一场灾难。

Do not do this.
It's a recipe for disaster.

这篇关于C#创建一个深度复制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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