📄 7-10.cs
字号:
//程序7-10
using System;
class Student
{
public int studID;
public string studName;
}
public class Department
{
public int DepartmentID;
public Department()
{ }
public Department(int i)
{
DepartmentID=i;
}
}
class CollegeStudent: Student,ICloneable
{
public Department Dept; // 引用类型
public CollegeStudent(string nm, int sID, int dID)
{
studID=sID;
studName=nm;
Dept= new Department( dID);
}
// 实现ICloneable接口中的Clone方法,完成深复制
public object Clone()
{
CollegeStudent CS=new CollegeStudent(this.studName, this.studID,this.Dept.DepartmentID);
return CS;
}
}
public class Test
{
public static void Main()
{
CollegeStudent S1 = new CollegeStudent( "Sam",2003179,001);
// 深复制,S2中的值从S1中的所有值复制,但是S1和S2分别占用不同的存储空间
CollegeStudent S2 = (CollegeStudent)S1.Clone();
// 改变S1中字段的值不影响S2中的值
S1.studName = "Bush";
//S1.studName = "Sam"; // string类型是一个特殊的引用类型,只要字符串内容相同,则引用和值均相等
S1.Dept.DepartmentID=002;
Console.WriteLine(S1.studID+" "+S1.studName+" "+S1.Dept.DepartmentID );
Console.WriteLine(S2.studID+" "+S2.studName+" "+S2.Dept.DepartmentID );
Console.WriteLine(Object.ReferenceEquals(S1,S2)); // false
Console.WriteLine(Object.ReferenceEquals(S1.studName,S2.studName)); // false
Console.WriteLine(Object.ReferenceEquals(S1.Dept.DepartmentID,S2.Dept.DepartmentID)); // false
Console.WriteLine(Object.Equals(S1.Dept.DepartmentID,S2.Dept.DepartmentID)); // false
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -