链式构造函数中自定义对象的聋价值

时间:2016-02-29 19:07:52

标签: c# constructor

关于构造函数链接我是reading我想知道,如果一个类中有一个子实例对象,例如下面的Course类,它应该如何用教授对象实例化?

public Course(string courseCode, string courseTitle, Professor teacher)
{
    if(String.IsNullOrWhiteSpace(courseCode))
    {
      throw new ArgumentNullException("Course Code Cannot Be Empty");
    }  

    this.courseCode = courseCode;

    if(String.IsNullOrWhiteSpace(courseTitle))
    {
      throw new ArgumentNullException("Course Title Cannot Be Empty");
    }
    this.courseTitle = courseTitle;

       this.prof = Professor.Clone(teacher);
 }

 public Course(string courseCode, string courseTitle)
        :this(courseCode,courseTitle,new Professor())
 {


 }

Professor class:

 public int id {get; private set; }
 public string firstName{get; private set;}
 public string lastName {get; private set;}

 public Professor(int ID, string firstName, string lastname)
 {
      this.id = ID;

      if(String.IsNullOrWhiteSpace(firstName))
      {
          throw new ArgumentNullException("first name Cannot be Null");
      }

      this.firstName = firstName;

      if(String.IsNullOrWhiteSpace(lastname))
      {
        throw new ArgumentNullException("last name cannot be null");
      }
      this.lastName = lastname;
  }

链接问题中的评论表明:

  

我认为链接构造函数时的最佳实践是调用   具有较少参数的参数的构造函数,   提供默认值。

我的Course类有一个professor对象作为参数之一。如果用户要创建一个没有教授的课程,教授的默认值应该是什么?

3 个答案:

答案 0 :(得分:1)

public Course(string courseCode, string courseTitle)
        :this(courseCode,courseTitle,new Professor())
 {

 }

在这个你不应该实例化新教授(),因为你没有任何教授。

public Course(string courseCode, string courseTitle)
        :this(courseCode,courseTitle,null)
 {

 }

当你想要创建没有教授的课程时使用这个构造函数,并且仅当教授对象在其他构造函数中不为null时才分配教授对象。

答案 1 :(得分:0)

  

如果用户要创建一个没有教授的课程,教授的默认值应该是什么?

设计方法应该提供对默认教授的答案,当一个人无法直接关联时。否则,作为开发人员,您需要创建默认教授,这只是一个最低限度的信息实例,可以在系统的未来处理中进行处理和更新。

构造函数链接背后的想法是简单地将重载的构造函数组织到集中常见的实例化操作,这样就不会重复它们。

答案 2 :(得分:0)

如果Professor在没有名称或ID的情况下不能存在,那么我就不会在Course中创建一个默认教授的重载构造函数。您将管理一个Course null实例,需要Professor教授。

如果可以的话,你想要一位普通教授" John Smith"那么我会让public class Professor { ... private static Professor _default; public static Professor Default { get { if (_default == null) _default = new Professor(-1, "John", "Smith"); return _default; } } } 类指定一个"空"教授的意思是(虽然我不推荐这个):

Course

然后将public Course (string courseCode, string courseTitle) : this(courseCode, courseTitle, Professor.Default) 中的重载构造函数更改为:

if (myProfInstance == Professor.Default)
    // insert into DB, for example

这些职责分离将使您的代码更易于维护,默认教授的单例实例将允许您稍后执行以下操作:

->execute()
相关问题