愚蠢的问题.
假设我有一堆人物对象,他们的字段都填充了数据,我有一个员工类型,派生自人员类,并且有与员工相关的额外字段.如何获取特定现有人员对象的员工对象?即如何将人物对象传递给员工?
如果此人是作为员工创建的,那么只需执行:
Person person = new Employee(); // for some reason ... Employee emp = (Employee)person;
如果这个人只是一个人:你不能; 您可以让员工封装 Person - 或者您可以复制字段:
class Employee { // encapsulation private readonly Person person; public Person {get {return person;}} public Employee(Person person) {this.person = person;} public Employee() : this(new Person()) {} }
要么
class Employee : Person { // inheritance public Employee(Person person) : base(person) {} public Employee() {} } class Person { public Person(Person template) { this.Name = template.Name; // etc } public Person() {} }