C# Why can't interfaces implement methods like this? What is a workaround to solve my issue? -


why can't interfaces implement methods this?

public interface itargetableunit {         //returns whether object of class implements interface targetable      bool unitcanbetargeted(){         bool targetable = false;         if(this insect){             targetable = (this insect).isfasterthanlight();         }         else if(this fighterjet){             targetable = !(this fighterjet).flying;         }         else if(this zombie){             targetable = !(this zombie).invisible;         }         return targetable;     } } 

insect, , zombie derives base class creature, , fighterjet derives class machine however, not creature-s targetable , not use itargetableunit inteface.

is there workaround solve issue facing?

like said can't define behaviour interfaces. inherite interface specific classes.

public interface itargetableunit  {       bool unitcanbetargeted();  }  public class insect : itargetableunit //you can add other interfaces here {       public bool unitcanbetarget()      {           return isfasterthanlight();      } }  public class ghost : itargetableunit  {      public bool unitcanbetarget()      {           return !flying();      } }  public class zombie : itargetableunit {      public bool unitcanbetarget()      {           return !invisible();      } } 

Comments

Popular posts from this blog

routing - AngularJS State management ->load multiple states in one page -

python - GRASS parser() error -

Swift game error message -