Lev*_*arc 5 c# generics polymorphism abstract-class overriding
我有一个关于派生,多态和方法签名的问题
我有课
public abstract class PaymentMethod
{
public abstract float GetSalary (Employee employee,Vehicule vehicule)
}
Run Code Online (Sandbox Code Playgroud)
和另外两个人
public class MarinePaymentMethod : PayementMethod
{
public override float GetSalary (Sailor sailor,Boat boat)
}
public class AirPaymentMethod : PayementMethod
{
public override float GetSalary (Pilot pilot,Plane plane)
}
Run Code Online (Sandbox Code Playgroud)
我们还假设:
public class Sailor : Employee{}
public class Pilot : Employee{}
public class Boat: Vehicule{}
public class Plane: Vehicule{}
Run Code Online (Sandbox Code Playgroud)
所以,"问题"是这个代码不能编译,因为签名不一样.
我强制保留基本签名GetSalary(员工员工,Vehicule vehicule)
然后我必须投在派生付款方式,这样我可以使用的特定成员Pilot,Sailor,Boat,Plane在这些具体的付款方式.
我的第一个问题是:连续投射不是难闻的气味吗?
我的第二个问题是:如何制作更优雅的代码设计?我在考虑Generics,并创建一个这样的类:
public abstract class PaymentMethod<T, U> where T: Employee where U: Vehicule
Run Code Online (Sandbox Code Playgroud)
但是在我的代码中,我意识到我必须把泛型几乎放在我使用支付方法的所有地方,它会使代码变得沉重.还有其他方法吗?
非常感谢
就我个人而言,我会这样做:
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{}
Run Code Online (Sandbox Code Playgroud)
这对于多态性和重载方法都适用——尽管采用 an 的方法Employee需要特定类型的员工是不常见的。