派生类和带有派生参数的覆盖方法:如何更好地编码

本文关键字:派生 何更好 更好 编码 方法 参数 覆盖 | 更新日期: 2023-09-27 18:34:28

我有一个关于推导、多态性和方法签名的问题

我有课

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{}

所以,"问题"是这段代码不编译,因为签名不一样。

我强制保留基本签名 Get薪水(员工员工,车辆(

然后我必须投射派生支付方式,这样我就可以在这些特定的支付方式中使用PilotSailorBoatPlane的特定成员。

我的第一个问题是:连续投掷不是难闻的气味?

我的第二个问题是:如何做出更优雅的代码设计?我在考虑泛型,并创建一个这样的类:

public abstract class PaymentMethod<T, U> where T: Employee where  U: Vehicule 

但是在我的代码中,我意识到我必须将通用几乎放在我使用支付mehod类的任何地方,这会使代码变得沉重。 还有其他解决方案吗?

多谢

派生类和带有派生参数的覆盖方法:如何更好地编码

就个人而言,我会这样做:

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的方法需要特定类型的员工是不寻常的。