以下只是解释我难以理解的问题的示例代码:
假设我有以下教授课程,请注意公共获取者和设置者:
public class Professor
{
public string id {get; set; }
public string firstName{get; set;}
public string lastName {get; set;}
public Professor(string ID, string firstName, string lastname)
{
this.id = ID;
this.firstName = firstName;
this.lastName = lastname;
}
}
和课程:
public class Course
{
string courseCode {get; private set;}
string courseTitle {get; private set;}
Professor teacher {get; private set;}
public Course(string courseCode, string courseTitle, Professor teacher)
{
this.courseCode = courseCode;
this.courseTitle = courseTitle;
}
}
我将如何在 Course 类中制作教授对象的防御性副本?此处提供的示例使用日期对象就是这样做的。
fDateOfDiscovery = new Date(aDateOfDiscovery.getTime());
可以对 Course 类中的教授对象做同样的事情吗?
更新:
接受提供的答案是我想出的,对吗?
public class Professor
{
public string id {get; set; }
public string firstName{get; set;}
public string lastName {get; set;}
Professor(string ID, string firstName, string lastname)
{
this.id = ID;
this.firstName = firstName;
this.lastName = lastname;
}
//This method can be either static or not
//Please note that i do not implement the ICloneable interface. There is discussion in the community it should be marked as obsolete because one can't tell if it's doing a shallow-copy or deep-copy
public static Professor Clone(Professor original)
{
var clone = new Professor(original.id, original.firstName, original.lastName);
return clone;
}
}
//not a method, but a constructor for Course
public Course (string courseCode, string courseTitle, Professor teacher)
{
this.courseCode = courseCode;
this.courseTitle = courseTitle;
this.teacher = Professor.Clone(teacher)
}