Any automatic way to clone a data object?

I have a bunch of simple data objects of different types (all properties are writable, there is no hidden state). Is there any automated way to clone such objects? (yes, I know a way to clone them manually. I just don’t want ^ _ ^)

+3
source share
5 answers

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

+4
source

Serialization and deserialization will clone your object. Of course, the object must 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);
    }
}
+3
source

IClonable , , .

( , ) - :

    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;
    }

, . , BindingFlags.NonPublic GetFields.
, , . , .

+1

. , . ,

0
using System.Web.Helpers;

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

Source: https://habr.com/ru/post/1795050/


All Articles