Create a Deep Copy in C#

后端 未结 8 2136
孤独总比滥情好
孤独总比滥情好 2020-12-04 01:48

I want to make a deep copy of an object so I could change the the new copy and still have the option to cancel my changes and get back the original object.

My proble

8条回答
  •  感情败类
    2020-12-04 02:01

    Ok, I modified your routine a little bit. You'll need to clean it up but it should accomplish what you want. I did not test this against controls or filestreams, and care should be taken with those instances.

    I avoided Memberwise clone for Activator.CreateInstance. This will create new Instances of reference types and copy value types. If you use objects with multi-dimensional arrays you will need to use the Array Rank and iterate for each rank.

        static object DeepCopyMine(object obj)
        {
            if (obj == null) return null;
    
            object newCopy;
            if (obj.GetType().IsArray)
            {
                var t = obj.GetType();
                var e = t.GetElementType();
                var r = t.GetArrayRank();
                Array a = (Array)obj;
                newCopy = Array.CreateInstance(e, a.Length);
                Array n = (Array)newCopy;
                for (int i=0; i

提交回复
热议问题