gpt4 book ai didi

c# - 链式构造函数中自定义对象的默认值

转载 作者:太空宇宙 更新时间:2023-11-03 12:50:35 24 4
gpt4 key购买 nike

<分区>

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

链接问题中的评论表明:

I think that the best practice when chaining constructors is to call the constructor with more arguments from the one with less arguments, providing default values.

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com