Function to clone an arbitrary object

微笑、不失礼 提交于 2019-12-05 16:19:47

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!

You can simply Serialize and Deserialize an object to make a clone.
The following function will do that:

public object Clone(object obj)
{
    MemoryStream ms = new MemoryStream();
    BinaryFormatter bf = new BinaryFormatter();
    bf.Serialize(ms, obj);
    ms.Position = 0;
    object obj_clone = bf.Deserialize(ms);
    ms.Close();
    return obj_clone;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!