C # in deep and shallow copy copy

First one sentence at a shallow copy and deep copy of what it means:

As if she did not understand, then two sentences of it.

First, whether it is deep or shallow copy copies are for reference object (Detailed: https://www.cnblogs.com/personblog/p/11308831.html )

If a shallow copy, the copy of the object in the object reference is a direct reference to the copied object (the same thing);

If a deep copy, then copy objects referenced objects are also copied to the new copy of the new object.

Why is for reference objects, because the value of the object is directly copied.

Directly on the bar code, then look at how to deal with the problem shallow copy;

UserDTO a = new UserDTO() { Name = "Lee", ID = "1" };
UserDTO b = new UserDTO();
b = a;
Console.WriteLine(b.Equals(a));
Console.WriteLine("-----------");
b.Name = "Mac";
Console.WriteLine(a.Name);

Wherein UserDTO is a class, only the two fields Name and ID

Output:

True

Mac

Illustrates a and b is the same thing, which is a shallow copy, the reason that class is a reference type, instead of a value type

How shallow copy that made a deep copy of the results so far?

There are three methods (see: https://www.cnblogs.com/TheBob/p/9414014.html ):

On the code, these two methods can be:

     //方法一    
     public static void DeepCopy<T>(T _raw,T _toObj)where T:class
        {
            Type type = _raw.GetType();
            object o = Activator.CreateInstance(type);
            PropertyInfo[] PI = type.GetProperties();
            for (int i = 0; i < PI.Length; i++)
            {
                PropertyInfo P = PI[i];
                P.SetValue(o, P.GetValue(_raw));
            }
            _toObj = o as T;
            return;
        }
     //方法二
        public static T DeepCopy<T>(T _raw)
        {
            Type type = _raw.GetType();
            object o = Activator.CreateInstance(type);
            PropertyInfo[] PI = type.GetProperties();
            for (int i = 0; i < PI.Length; i++)
            {
                PropertyInfo P = PI[i];
                P.SetValue(o, P.GetValue(_raw));
            }         
            return (T)o;
        }

Calling the situation:

            UserDTO a = new UserDTO() { Name = "Lee", ID = "1" };
            UserDTO b = new UserDTO();
            b = a;
            Console.WriteLine(b.Equals(a));
            //DeepCopy(a, b);
            b = DeepCopy(a);
            Console.WriteLine("-----------");
            Console.WriteLine(b.Equals(a));
            b.Name = "Mac";
            Console.WriteLine(a.Name);            

Output:

 

 We're done!

Guess you like

Origin www.cnblogs.com/LeeSki/p/12162055.html