编译器无法识别属性

时间:2019-01-08 18:31:42

标签: c# oop console-application

我有两个班级HumanEmployee Employee继承了Human,如图所示, Human具有两个属性(nameage), Employee具有两个属性(agesalary

当我尝试在一行定义中从Human创建实例时,它会看到所有HumanEmployee属性 但是,当我拆分定义时,它只会看到Human个属性,并且会在Employee个属性上引发错误!

我不明白为什么会这样

这是我的代码:

public class Human
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public class Employee : Human
{
    public new int Age { get; set; } 
    public decimal Salary { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        Human h = new Employee { Name = "Ahmed", Age = 24, Salary = 1500 };

        Human h2 = new Employee();
        h2.Name = "Ahmed";
        h2.Age = 10;
        h2.Salary = 5000; // h.salary has a red underline
    }
}

2 个答案:

答案 0 :(得分:1)

实际上hEmployee类型的 ,您告诉编译器将其作为Human的实例进行线程化。要访问薪金属性,可以将h声明为Employee或将h转换为员工。

Employee h = new Employe {...};
//...
h.salary = 5000;

// or
((Employee) h).salary = 5000; //if you know h is an employee

// or
Employee employee = h as Employee
if(employee != null)
    employee.salary = 50000;

// or, if you can use pattern matching
if(h is Employee employee)
    employee.salary = 50000;

答案 1 :(得分:1)

将对象强制转换为层次结构的基本类型时,它只能访问该特定类型可用的成员。如果您想访问Employee成员,则您的对象必须是Employee类型。

Employee employee = new Employee();
employee.salary = 5000; // No issue, the Employee type knows it has a salary
Human human = employee;
human.salary = 2000; // Compilation error, the Human type doesn't know anything about the salary property available to the derived Employee type