以下是示例代码,用于解释我难以理解的问题:

可以说我有以下教授课程,请注意公众参与者和二传手:

    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;

    }
}


在课程课程中,我该如何对Professor对象进行防御性复制? here提供的示例使用date对象执行此操作。

fDateOfDiscovery = new Date(aDateOfDiscovery.getTime());


可以对Course类中的Professor对象做同样的事情吗?

更新:

根据我提供的答案,这是对的吗?

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)

}

最佳答案

您可以克隆您的教授实例。

克隆逻辑应在Professor类之内。

然后,您可以在Course构造函数中收到一个已经克隆的Professor实例。

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;
 }
}


然后,当您调用新的Course时,将执行此操作

public Course AddCourse(string courseCode, string courseTitle, Professor original)
{
  var clonedProfessor = Professor.Clone(original);
  var course = new Course(courseCode, courseTitle, clonedProfessor);
  return course;
}

09-27 11:32