【问题标题】:How can I initialize a base class's properties when I instantiate a derived class through its constructor? [duplicate]通过构造函数实例化派生类时,如何初始化基类的属性? [复制]
【发布时间】:2021-04-27 05:21:12
【问题描述】:

我必须创建两个类。基类是Employee,它需要 2 个受保护的字段。一个字符串Name 和一个整数Number。然后我必须创建一个名为ProductionWorker 的派生类,它有4 个属性。前两个是从基类继承的 2 个属性。接下来的两个是 double PayRate 和 int ShiftNum。用户在表单上输入此数据。单击显示按钮后,需要将这 4 个数据点作为属性初始化到 ProductionWorker 对象中。然后使用该对象,我必须将此数据显示为字符串。

我已经读过:派生类的构造函数之后的基数。但是我仍然无法初始化 ProductionWorker,因为它没有采用全部 4 个参数?

namespace Employee_Form
{
    class Employee
    {
        protected string Name { get; set; }
        protected int Number { get; set; }

        public Employee(string name, int number)
        {
            this.Name = name;
            this.Number = number;
        }
    }
}

命名空间 Employee_Form { 类ProductionWorker:员工 { 受保护的静态新字符串名称{获取;放; } protected static new int Number { get;放; } 受保护的 int ShiftNum { 得到;放; } 受保护的双倍工资率 { 得到;放; }

    public ProductionWorker(int shiftNum, double payRate) : base (Name, Number)
    {
        this.ShiftNum = shiftNum;
        this.PayRate = payRate;
    }

    public string showData()
    {
       
    }
}

}

namespace Employee_Form
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            ProductionWorker worker = new ProductionWorker(Convert.ToInt32(textBox3.Text),
                                                           Convert.ToDouble(textBox4.Text),
                                                           textBox1.Text,
                                                           textBox2.Text);
        }
    }
}

【问题讨论】:

  • “我仍然无法初始化 ProductionWorker,因为它没有采用全部 4 个参数?” -- 只是因为您没有提供它们。所以提供他们。有关调用所需的基本构造函数的所有详细信息,请参阅副本。当然,您的代码的另一个大问题是您重新声明了基本属性NameNumber,使用new 隐藏它们。不要那样做。

标签: c#


【解决方案1】:

您的子类必须在构造函数中包含所有 4 个参数。即:

public ProductionWorker(string name, int number, int shiftNum, double payRate) : base (name, number)

另一种方法是没有明确的讲师,并使用初始化程序的语法。即:

ProductionWorker worker = new ProductionWorker(textBox1.Text, textBox2.Text)
{
    ShiftNum = Convert.ToInt32(textBox3.Text),
    PayRate = Convert.ToDouble(textBox4.Text)
};

^ 要让它工作,你再次需要从子类中删除显式构造函数。

【讨论】:

    猜你喜欢
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多