如何将固定参数传递给基构造函数

本文关键字:构造函数 参数传递 | 更新日期: 2023-09-27 18:06:34

什么

我有这个编码练习,基类构造函数应该能够使用输入参数定义自定义属性值,但派生类应该将此属性设置为固定值。

练习文本片段:

  1. "定义一个类别Manager…经理每月还有奖金,应该在施工时指定…">
  2. 'u2028"定义一个类DirectorDirector类应该是从Manager类派生而来的。董事只是一个每月有20000固定奖金的经理……在实现Director类时,要特别注意正确实现构造函数。该类除了构造函数之外还需要什么吗?">

问题

那么,我如何通过在派生类中只有构造函数来设置这个固定值呢?此外:子类对象的创建者根本不应该设置此属性(monthlyBonus(。

尝试

//Manager inherits Employee (not interesting in this context)
public Manager(string name, int salaryPerMonth, int monthlyHours, int monthlyBonus) : base(name, salaryPerMonth)
    {
        MonthlyHours = monthlyHours;
        Bonus = monthlyBonus;
    }
public class Director : Manager
{
    public Director(string name, int salaryPerMonth, int monthlyHours, int monthlyBonus = 20000) : base(name, salaryPerMonth, monthlyHours, monthlyBonus)
    {
        //base.Bonus = 20000;
    }
}
  • 我曾想过在构造函数内部生成一个变量时删除Director类中的输入参数monthlyBonus,但由于基类构造函数首先被调用,我想这是行不通的。

  • 我还考虑过将输入参数值设置为可选值,但调用方可以更改此值,因此这也不被接受。

如何将固定参数传递给基构造函数

您可以直接在基本构造函数中传递值

public class Director : Manager
{
    public Director(string name, int salaryPerMonth, int monthlyHours,)  
           :base(name, salaryPerMonth, monthlyHours, 20000)
    { 
    }
}

简单的答案是,您只需要更改构造函数声明:

public Director(string name, int salaryPerMonth, int monthlyHours)
    : base(name, salaryPerMonth, monthlyHours, 20000) { }

也就是说,省略(正如您已经做的那样(monthlyBonus参数,并在使用base调用基本构造函数时对该值进行硬编码。

由于这显然是一个课堂练习,我鼓励您提出一些问题,重点是为什么您还没有意识到可以这样做,这样您就可以更好地理解base()构造函数调用是如何工作的。

现在,我只想指出,它与任何其他方法调用本质上是一样的,您可以用它做任何其他方法引用中可以做的事情。参数可以是您想要的任何表达式;它们不需要只是派生构造函数中参数的重复。