how to call derived function using base class object

前端 未结 4 725
暗喜
暗喜 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:13

    Without virtual declared on the method, the base method will always be called because you declared your variable as Parent. If you can't append virtual to the base class, then you can only either declare the variable as Child, or cast it to Child and call your GetNo method:

    Child p = new Child();
    p.GetNo();
    

    Or:

    Parent p = new Child();
    ((Child)p).GetNo();
    

提交回复
热议问题