在 Silverlight 的扩展方法中使用反射进行深度复制? [英] Deep Copy using Reflection in an Extension Method for Silverlight?

查看:35
本文介绍了在 Silverlight 的扩展方法中使用反射进行深度复制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图找到一种通用的扩展方法,它使用反射创建对象的深层副本,这将在 Silverlight 中工作.在 Silverlight 中,使用序列化的深层复制并不是那么好,因为它以部分信任的方式运行,并且 BinaryFormatter 不存在.我也知道反射会比克隆序列化更快.

So I'm trying to find a generic extension method that creates a deep copy of an object using reflection, that would work in Silverlight. Deep copy using serialization is not so great in Silverlight, since it runs in partial trust and the BinaryFormatter does not exist. I also know that reflection would be faster then serialization for cloning.

如果有一种方法可以复制公共、私有和受保护的字段,并且是递归的,这样它就可以复制对象中的对象,并且还能够处理集合、数组等.

It would be nice to have a method that works to copy public, private and protected fields, and is recursive so that it can copy objects in objects, and that would also be able to handle collections, arrays, etc.

我在网上搜索过,只能找到使用反射的浅拷贝实现.我不明白为什么,因为你只能使用 MemberwiseClone,所以对我来说,这些实现是无用的.

I have searched online, and can only find shallow copy implementations using reflection. I don't understand why, since you can just use MemberwiseClone, so to me, those implementations are useless.

谢谢.

推荐答案

对于数据契约对象,我们使用了以下辅助方法在 Silverlight 中进行深度克隆:

For data contract objects we have used the following helper method for deep cloning within Silverlight:

public static T Clone<T>(T source)
        {

            DataContractSerializer serializer = new DataContractSerializer(typeof(T));
            using (MemoryStream ms = new MemoryStream())
            {
                serializer.WriteObject(ms, source);
                ms.Seek(0, SeekOrigin.Begin);
                return (T)serializer.ReadObject(ms);
            }
        }

这样使用:

var clone = CloneHelper.Clone<MyDTOType>(dtoVar);

这篇关于在 Silverlight 的扩展方法中使用反射进行深度复制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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