我有关于派生,多态和方法签名的问题
我有课
public abstract class PaymentMethod
{
public abstract float GetSalary (Employee employee,Vehicule vehicule)
}
和另外两个人
public class MarinePaymentMethod : PayementMethod
{
public override float GetSalary (Sailor sailor,Boat boat)
}
public class AirPaymentMethod : PayementMethod
{
public override float GetSalary (Pilot pilot,Plane plane)
}
我们还假设:
public class Sailor : Employee{}
public class Pilot : Employee{}
public class Boat: Vehicule{}
public class Plane: Vehicule{}
所以,“问题”是这段代码不能编译,因为签名不一样。
我强制保留基本签名GetSalary(员工员工,Vehicule vehicule)
然后我必须使用派生付款方式,以便我可以在这些特定付款中使用Pilot
,Sailor
,Boat
,Plane
的特定成员方法
我的第一个问题是:连续投射不是难闻的气味吗?
我的第二个问题是:如何制作更优雅的代码设计?我正在考虑泛型,并创建一个这样的类:
public abstract class PaymentMethod<T, U> where T: Employee where U: Vehicule
然后在我的代码中,我意识到我必须在所有使用支付方法类的地方放置泛型,这会使代码变得沉重。还有其他解决方案吗?
非常感谢
答案 0 :(得分:1)
就个人而言,我会这样做:
public abstract class PaymentMethod {
public decimal GetSalary(Employee employee, Vehicle vehicle) {
return GetSalaryImpl(employee, vehicle);
}
protected abstract decimal GetSalaryImpl(Employee employee, Vehicle vehicle);
}
public class MarinePaymentMethod : PaymentMethod {
public decimal GetSalary(Sailor sailor,Boat boat)
{ throw new NotImplementedException(); /* your code here */ }
protected override decimal GetSalaryImpl(Employee employee, Vehicle vehicle) {
return GetSalary((Sailor)employee, (Boat)vehicle);
}
}
public class AirPaymentMethod : PaymentMethod {
public decimal GetSalary(Pilot pilot, Plane plane)
{ throw new NotImplementedException(); /* your code here */ }
protected override decimal GetSalaryImpl(Employee employee, Vehicle vehicle) {
return GetSalary((Pilot)employee, (Plane)vehicle);
}
}
public class Employee {}
public class Vehicle{}
public class Sailor : Employee{}
public class Pilot : Employee{}
public class Boat: Vehicle{}
public class Plane: Vehicle{}
这适用于多态和重载方法 - 尽管采用Employee
的方法需要员工的特定类型,这是不寻常的。