功能克隆任意对象 [英] Function to clone an arbitrary object

查看:117
本文介绍了功能克隆任意对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在寻找一种方法来克隆未在编译时已知对象(或运行时,我认为)。这个问题的确切措辞是写可以克隆任意对象的函数,例如




  • 传递不明物体的功能。

  • 返回对象的深层复制。



我猜我将需要使用反射来读函数和变量,然后一些如何创建一个新的对象,并指定这些值了。我可以只使用Type.GetType()来查找类型并创建一个新实例,然后使用该对象的拷贝构造函数。但我不知道一个给定的类是否将有一个执行(深),或该问题是否要求这样的解决方案(没有帮助,我不明白所需的结局是什么!)。



有人能指导我在正确的方向,用类/接口要求,以及伪代码,如果你感觉大方,要实现这一目标?


< DIV CLASS =h2_lin>解决方案

这可以通过利用

 键入newObjectType =实现orgObject.GetType()

,然后调用Activator.CreateInstance(newObjectType)。那么,什么,你需要做的就是通过对象的所有属性循环,并将它们设置新对象。这也可通过反射完成。



通过(每个的PropertyInfo在orgObject.GetType)循环。的GetProperties(),并设置新对象的值。



这的确应该创建该对象的深度拷贝,独立于它是什么类型



编辑:$我上面所解释的方法乙$ b未测试的代码示例

 键入newObjectType = orgObject.GetType(); 
对象NEWOBJECT = Activator.CreateInstance(newObjectType);

的foreach(在orgObject.GetType VAR propInfo()的GetProperties())
{
对象orgValue = propInfo.GetValue(orgObject,NULL);

//设置新对象
propInfo.SetValue(NEWOBJECT,orgValue,NULL)的价值;
}



希望你得到了一些清晰!


I'm looking at a way to clone an object that is not known at compile time (or run-time, I think). The exact wording of the question is "Write a function that can clone an arbitrary object" E.g.

  • Pass unknown object to function.
  • Return a Deep Copy of object.

I'm guessing I will need to use Reflection to read the functions and variables, and then some how create a new object and assign these values to it. I could just use the Type.GetType() to find the type and create a new instance, then use this known object's copy constructor. But I'm not sure whether a given class will have one implemented (Deep), or whether the question is asking for such a solution (doesn't help that I don't understand what the required outcome is!).

Could someone guide me in the right direction, with Classes/Interfaces required, and Pseudo code if you're feeling generous, to achieve this?

解决方案

This can be achieved by utilizing the

Type newObjectType = orgObject.GetType()

and then calling the Activator.CreateInstance(newObjectType). What you then has to do is loop through all properties of the object and set them on the new object. This can as well be done via reflection.

Loop through each PropertyInfo in orgObject.GetType().GetProperties() and set the value on the new object.

This should indeed create a "deep" copy of the object, independent of what type it is.

EDIT: Untested code example of the method I explained above.

Type newObjectType = orgObject.GetType();
object newObject = Activator.CreateInstance(newObjectType);

foreach (var propInfo in orgObject.GetType().GetProperties())
{
    object orgValue = propInfo.GetValue(orgObject, null);

    // set the value of the new object
    propInfo.SetValue(newObject, orgValue, null);
}

Hope you got some clarity!

这篇关于功能克隆任意对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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