深拷贝与浅拷贝

浅拷贝

浅拷贝是字段的被拷贝,而字段的引用的对象不会被拷贝,拷贝对象和源对象仅仅是引用名称有所不同,他们公用一份实体,改变其中一个都会影响到因为一个对象。

void Main()
{ 
    Student s1=new Student("objectboy",27);
    Student s2=s1;
    s2.Age=20;
    s1.ShowInfo();
    s1.Age=11;
    s2.ShowInfo();
}

public class Student{
    public string Name;
    public int Age;
    public Student(string name,int age){
        Name=name;
        Age=age;
    }
    public void ShowInfo(){
        Console.WriteLine("{0}'s age is {1} ",Name,Age);
    }
}
输出:
objectboy's age is 20 
objectboy's age is 11 

 深拷贝

对象的字段拷贝,同时对象的引用也被拷贝,不共用一个对象,改变其中一个对象不会影响到另外一个对象(一般值类型的拷贝就是深拷贝)。

void Main()
{
    int i=0;
    int j=i;
    i=2;
    Console.WriteLine(i);
    Console.WriteLine(j);
}
输出:
2
0

 浅拷贝实现

void Main()
{
    var sourceEnrollment=new Enrollment();
    sourceEnrollment.students.Add(new Student(){Name="objectboy",Age=27});
    sourceEnrollment.students.Add(new Student(){Name="hky",Age=27});
    
    Enrollment cloneStudents=sourceEnrollment.Clone() as Enrollment;  //克隆
    sourceEnrollment.ShowEnrollmentInfo();
    cloneStudents.ShowEnrollmentInfo();
    
    Console.WriteLine("------------------------------");
    
    cloneStudents.students[0].Name="boyobject";
    cloneStudents.students[0].Age=22;
    sourceEnrollment.ShowEnrollmentInfo();
    cloneStudents.ShowEnrollmentInfo();
}

class Enrollment:ICloneable{
    public  List<Student> students=new List<Student>();
    public void ShowEnrollmentInfo(){
        foreach (var element in students)
        {
            Console.WriteLine("{0}'s age is {1}",element.Name,element.Age);
        }
    }
    public object Clone(){
        return MemberwiseClone();
    }
}
public class Student{
    public string Name{get;set;}
    public int Age{get;set;}
}
输出:
objectboy's age is 27
hky's age is 27
objectboy's age is 27
hky's age is 27
------------------------------
boyobject's age is 22
hky's age is 27
boyobject's age is 22
hky's age is 27
原文地址:https://www.cnblogs.com/objectboy/p/4623231.html