c# - Derived class and override method with derived arguments : how to code it better? -


i have question derivation , polymorphism , method signature

i have class

public abstract class paymentmethod {        public abstract float getsalary (employee employee,vehicule vehicule) } 

and 2 others

public class marinepaymentmethod : payementmethod {     public override float getsalary (sailor sailor,boat boat) }  public class airpaymentmethod : payementmethod {     public override float getsalary (pilot pilot,plane plane) } 

we assume :

public class sailor : employee{} public class pilot : employee{} public class boat: vehicule{} public class plane: vehicule{} 

so, "problem" code not compile , because signatures not same.

i force keep base signature getsalary(employee employee, vehicule vehicule)

and must cast in derived payment method, can use specific members of pilot, sailor, boat, plane in these specific payment method.

my first question is: isn't bad smell cast continuously?

my second question is: how make more elegant code design ? thinking generics, , create class this:

public abstract class paymentmethod<t, u> t: employee  u: vehicule  

but in code realize must put generic everywhere use payment mehod class , make code heavy. other solutions ?

thanks lot

personally, i'd way:

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(); /* 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(); /* 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{} 

this works both polymorphism , overload approaches - although unusual method takes employee requires specific type of employee.


Comments

Popular posts from this blog

java - Plugin org.apache.maven.plugins:maven-install-plugin:2.4 or one of its dependencies could not be resolved -

Round ImageView Android -

How can I utilize Yahoo Weather API in android -