开发者

Any automated way to clone a data object?

开发者 https://www.devze.com 2023-02-14 05:10 出处:网络
I have a bunch of simple data objects of different types (all proper开发者_如何学JAVAties are writable, no hidden state). Is there any automated way to clone such objects?

I have a bunch of simple data objects of different types (all proper开发者_如何学JAVAties are writable, no hidden state). Is there any automated way to clone such objects? (yes, I know the way to clone them manually. Just don't want to ^_^)


Serialize them in a (memory)stream and deserialize them back.


Serializing and deserializing would clone your object. Of course, the object would need to be serializable.

public static T Clone<T>(T source) 
{
    IFormatter formatter = new BinaryFormatter();
    using (Stream stream = new MemoryStream())
    {
        formatter.Serialize(stream, source);
        stream.Seek(0, SeekOrigin.Begin);
        return (T)formatter.Deserialize(stream);
    }
}


The best approach is to implement IClonable interface in all objects but in case that objects developed not by you its not appropriate way for you.

The second way ( most universal in my opinion) is to use reflection:

    public T CommonClone<T>(T Source)
    {
        T ret = System.Activator.CreateInstance<T>();

        Type typeDescr = typeof(T);

        if (typeDescr.IsClass != true)
        {
            ret = Source;
            return ret;
        }

        System.Reflection.FieldInfo[] fi = typeDescr.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); 

        for (int i = 0; i < fi.Length; i++)
        {
            fi[i].SetValue(ret, fi[i].GetValue(Source));
        }

        return ret;
    }

The code above will copy both public and private fields. If you need to cope only public ones, just remove BindingFlags.NonPublic from GetFields method call.
This way not specified any limitation on objects which can use. Its working both for classes and structures.


using System.Web.Helpers;

public static T Clone<T>(T source)
{
    return Json.Decode<T>(Json.Encode(source));        
}


You might see this Deep cloning objects Take a look at second answer. I use it all the time and it works great. The only drawback of this solution is the fact that class must be serializable

0

精彩评论

暂无评论...
验证码 换一张
取 消