问题描述
假如我有两个类:
类Employee
和
类AdvancedEmployee:员工
我知道这样的事情是行不通的,因为我不能垂头丧气C#的:
VAR员工=新员工();
无功先进=员工为AdvancedEmployee;
我的问题是:如何在有效的方式完成垂头丧气?
其实我有AdvancedEmployee一个构造函数劳动者作为参数,并用它来注入自己的价值观,基本上做一个克隆。
更新
要解决会得到重复,我改变了做法了一下数据,现在AdvancedEmployee包含一个雇员,而不是为一种本身。
示例:
类员工;
类AdvancedEmployee
{
私人员工
公共AdvancedEmployee(员工员工){
this.employee = $员工b
$ b}
}
创建界面。既然你不能修改员工,创建一个您拥有:
类EmployeeAdapter:IEmployee
{
私人雇员EMP;
公共EmployeeAdapter(员工EMP){this.emp = EMP; }
公众诠释SomeMethodInEmployee(){返回emp.SomeMethodInEmployee(); }
}
类AdvancedEmployee:IEmployee {}
Suppose I have two classes:
class Employee
and
class AdvancedEmployee:Employee
I know something like this won't work, as I can't downcast on C#:
var employee = new Employee();
var advanced = employee as AdvancedEmployee;
My question is: How to accomplish downcast in a efficient way? Actually I have a constructor on AdvancedEmployee that takes a Employee as parameter and use it to inject its values, basically making a clone.
Update
To solve the data that would get duplicated I changed the approach a bit and now AdvancedEmployee CONTAINS an employee rather than being one itself.Example:
class Employee;
class AdvancedEmployee
{
private employee
public AdvancedEmployee(Employee employee){
this.employee = employee
}
}
Create an interface. And since you can't modify Employee, create an adapter that you own:
class EmployeeAdapter : IEmployee
{
private Employee emp;
public EmployeeAdapter(Employee emp) { this.emp = emp; }
public int SomeMethodInEmployee() { return emp.SomeMethodInEmployee(); }
}
class AdvancedEmployee : IEmployee { }
这篇关于铸造基地例如在C#中派生类(垂头丧气)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!