how to call derived function using base class object

前端 未结 4 681
暗喜
暗喜 2021-01-14 04:43
class Parent
{
    public int GetNo()
    {
        return 1;
    }
}

class Child : Parent
{        
    public Child()
    {

    }

    public int GetNo()
    {           


        
4条回答
  •  执笔经年
    2021-01-14 05:27

    I have just come here so i could find a solution that doesn't use casts, but since i didn't find it here is one.

    Maybe it can be of help for someone.

    abstract class Parent
    {
        public int GetNo()
        {
            return GetNoImpl();
        }
    
        protected abstract int GetNoImpl();
    
    }
    
    class Child : Parent
    {        
        public Child()
        {
    
        }
    
        protected override int GetNoImpl();
        {                       
            return 2;
        }
    }
    
    Parent p = new Child();
    p.GetNo();
    

    Note: the parent class is abstract.

提交回复
热议问题