how to call derived function using base class object

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

    You can cast it:

    ((Child)p).GetNo();
    

    or

    if(p is Child)
        (p as Child).GetNo();
    
    0 讨论(0)
  • 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();
    
    0 讨论(0)
  • 2021-01-14 05:24

    You can force this with an explicit cast e.g.

    ((Child)p).GetNo();
    

    Or you can use hiding e.g.

    public new int GetNo()
    {
      return 2;
    }
    

    Though I think the latter only gets called if the variable is typed to the class that hides the method.

    If you really need to override a method properly and it's from a compiled DLL consider getting in touch with the developers to see whether they can make the method virtual (and if not why) or if an open source project just get the source code and modify it yourself.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题