我有两个班级Human
和Employee
Employee
继承了Human
,如图所示,
Human
具有两个属性(name
和age
),
Employee
具有两个属性(age
和salary
)
当我尝试在一行定义中从Human
创建实例时,它会看到所有Human
和Employee
属性
但是,当我拆分定义时,它只会看到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
}
}
答案 0 :(得分:1)
实际上h
是Employee
类型的 ,您告诉编译器将其作为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