简体   繁体   中英

Should I upcast before calling an inherited method

I am probably doing something way wrong here, but I have a Base class with multiple derived classes.

 public abstract class BaseItem : MonoBehaviour
    {
        public void LevelUp()
        {
           // do some common thing ... maybe increase damage
        }
    }
 public class RangedWeapon: BaseItem 
    {
      public new void LevelUp()
        {
            base.LevelUp();
            // do specific things here... maybe increase range.
        }
   }

 public class MeleeWeapon: BaseItem 
    {
      public new void LevelUp()
        {
            base.LevelUp();
            // do specific things here... 
        }
   }

In an inventory manager, I have a list of all items, and can call the LevelUp method on them. The issue, I think, is that I have a list of <BaseItem> s and the specific classes LevelUp is not called:

public void LevelUpItem(string itemName)
        {
            var item = AvailableItems.First(w => w.ItemName.Equals(itemName));
            
            item.LevelUp();
        }

My original thought is that I need to upcast the item before calling the LevelUp function. My second thought is that I'm doing something way wrong here.

My specific question is "How do I upcast safely" and my unasked question is, "should I consider a different approach to polymorphism?"

In C# you can use virtual keyword (also there is abstract modifier in case you don't want to have any default implemenation) for polymorphism :

public abstract class BaseItem : MonoBehaviour
{
    public virtual void LevelUp()
    {
       // do some common thing ... maybe increase damage
    }
}

And use override modifier to change the behavior in inheritors:

public class RangedWeapon: BaseItem 
{
  public override void LevelUp()
    {
        base.LevelUp();
        // do specific things here... maybe increase range.
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM