访问继承类的数据成员

本文关键字:数据成员 继承 访问 | 更新日期: 2023-09-27 18:17:40

所以我有4个类:Employee(基类),PartTime: Employee, FullTime: Employee, Manager: Employee。我试图访问唯一的,但不知道确切的方法。我试过选演员,但没用。这是我目前所知道的。

            Employee emp1 = new Manager();
            emp1.FirstName = txtFirst.Text;
            emp1.LastName = txtLast.Text;
            emp1.Ssn = Convert.ToInt32(txtSSN.Text);
            emp1.HireDate = Convert.ToInt32(txtHire.Text);
            emp1.TaxRate = Convert.ToDecimal(txtTax.Text);
            emp1.Email = txtEmail.Text;
            emp1.PhoneNum = Convert.ToInt32(txtPhone);
            if (emp1 is PartTime)
            {
                emp1.HourlyRate = txtRate.Text;
                emp1.HoursWorked = txtHrs.Text;
            } 
            if (emp1 is FullTime)
            {
                emp1.Salary = Convert.ToDecimal(txtSalary.Text);
                emp1.VacationDays = Convert.ToDouble(txtVacation.Text);
                emp1.SickDays = Convert.ToDouble(txtSick.Text);
                emp1.IsTaxExempt = comboTax.SelectedIndex == 0 ? true : false;
                emp1.HasInsurance = comboInsurance.SelectedIndex == 0 ? true : false;
            }
            if (emp1 is Manager)
            {
                (Manager)emp1.BonusEarned = Convert.ToDecimal(txtBonus.Text);
                (Manager)emp1.Department = comboDepartment.SelectedText;
                (Manager)emp1.OfficeLocation = txtOffice.Text;
            }

在这个例子中,Manager有属性BonusEarned, Department和OfficeLocation,但是Employee, FullTime和PartTime没有。

访问继承类的数据成员

试试这个(注意括号):

((Manager)emp1).BonusEarned = Convert.ToDecimal(txtBonus.Text);
((Manager)emp1).Department = comboDepartment.SelectedText;
((Manager)emp1).OfficeLocation = txtOffice.Text;

啊,我认为这只是无效的语法。你正在赋值语句的LHS中进行强制转换…事情不是这样的。Cast必须在RHS上,这样才能分配结果。请尝试这样做;

if (emp1 is Manager)
            {
                var man = (Manager)emp1
                man.BonusEarned = Convert.ToDecimal(txtBonus.Text);
                man.Department = comboDepartment.SelectedText;
                man.OfficeLocation = txtOffice.Text;
            }