加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 构造函数链接或使用命名/可选参数

发布时间:2020-12-15 22:31:50 所属栏目:百科 来源:网络整理
导读:我是一个非常新的程序员并且理解我们希望最小化代码冗余,因此当我们更新时,我们可以尽可能少地进行更改并最小化错误. 所以我有一个Student类,我想重载构造函数所以如果我回链接就像这样. public class Student{ string name; int Id; public Student() { } p
我是一个非常新的程序员并且理解我们希望最小化代码冗余,因此当我们更新时,我们可以尽可能少地进行更改并最小化错误.

所以我有一个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!

他们之间的另一个区别是使用反射.可选参数不会为您生成更多构造函数,如果使用反射调用构造函数,则不会应用默认值.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读