我是一个非常新的程序员并且理解我们希望最小化代码冗余,因此当我们更新时,我们可以尽可能少地进行更改并最小化错误.
所以我有一个Student类,我想重载构造函数所以如果我回链接就像这样.
public class Student { string name; int Id; public Student() { } public Student(string name) { this.name = name; } public Student(string name,int Id) :this(name) { this.Id = Id;
但这显然是不好的,因为我们想要一个构造函数中的所有代码是出于什么原因?易于阅读?
public Student() : this(null,0) { } public Student(string name) : this(name,0) { } public Student(string name,int Id) { this.name = name; this.Id = Id; }
如果我这样做,那么如果我们添加一个像字符串major这样的新字段会发生什么呢?如果我转发链接,那么我使用添加的字段创建一个新的重载构造函数.但现在我必须更改所有其他构造函数以调用新构造函数.如果我进行向后链接,我只需创建一个新的构造函数并调用前一个重载的构造函数.
public Student(string name,int Id,string major):this(name,Id) { this.major=major; }
这似乎比OOP更好,但我的教科书中的所有示例都显示了前向链接,并且没有说明为什么我不应该使用反向链接.
如果我使用命名/可选参数,那就更容易了.
public Student(string name = null,int Id = 0,string major = null) { this.name = name; this.Id = Id; this.major = major; }
如果我需要另一个字段,我只需要编辑唯一的构造函数.这似乎遵循OOP原则最好还是我错了?它至少消除了代码重复.我的任务是“按照OOP的原则实施学生课程”.我知道所有这些都是有效的,但是编码构造函数的最佳/可接受的方式之一是什么?我缺少命名/可选参数的缺点吗?作为一个初学者,有很多方法来编写这个,这是非常令人困惑的.
解决方法
没有最好的方法,因为它们不同,每种方法都有优点和缺点.
从C#1.0开始,独立构造函数和链式构造函数可用,在大多数情况下我们使用链式构造函数,但有时我们必须使用前者,如果两个构造函数有完全不同的东西要处理.
class Student { public Student() { DoSomething(); } public Student(string name) { this.Name = name; DoAnotherThing(); } }
与可选参数构造函数相比,上面两个更长,但说实话,它们更安全.考虑以下情况:
public class Student { public Student(string firstName = null,string lastName = null) { this.FirstName = firstName; this.LastName = lastName; } public string FirstName { get; set; } public string LastName { get; set; } } //it's working fine //var danny = new Student("danny","chen"); //as the business grows a lot of students need a middle name public Student(string firstName = null,string middleName = null,string lastName = null) { this.FirstName = firstName; this.MiddleName = middleName; this.LastName = lastName; } //for a better sequence the programmer adds middleName between the existing two,bang!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。