c# - Handling collections of objects through a switch statement -


i need have player equip item shown here:

iequiptable interface.

and method in in player class.

public void equip(iequiptable equipable)      {         switch (equipable.gettype())         {             case equipable weapons:                 this.weapon = equipable;                 break;              case equipable shield:                 this.shield = equipable                 break;                  //etc etc..         }     } 

i error switch experession must bool,char,string,integral, enum or corresponding nullable type.

i handle having equit method in each of weapon/shield etc classes , pass on player class parameter. feel illogical player should equipt item, not item equip it's self on player.

you have interface why don't make use of it?

public interface iequipable {     void equipon( player player ); }  public class shield : iequipable {     public void equipon( player player )     {         player.shield = this;     } }  public class weapons : iequipable {     public void equipon( player player )     {         player.weapon = this;     } } 

and code becomes

public void equip(iequiptable equipable)  {    equipable.equipon( );  } 

in fact, don't need method, has been reduced merely forwarding job proper class. everytime have iequipable call equipon method.


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -