如何使用基类对象调用派生函数 [英] how to call derived function using base class object

查看:93
本文介绍了如何使用基类对象调用派生函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Parent
{
    public int GetNo()
    {
        return 1;
    }
}

class Child : Parent
{        
    public Child()
    {

    }

    public int GetNo()
    {                       
        return 2;
    }
}

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

但它调用Base.GetNo().我知道如果我使用virutal,它将调用Child.GetNo() 但是我不能在Base中使用virutal,因为我必须从已经分布在DLL中的base派生我的类.所以我无法修改基类的现有功能.

But it calls Base.GetNo(). I know if I use virutal in base it will call Child.GetNo() But i can't use virutal in Base becuase i have to derive my class from base which is already distributed in DLL.So there's no way i can modify the existing functions of base class.

任何建议都是有价值的. 谢谢

Any sugguestions are valued. Thanks

推荐答案

您可以投射它:

((Child)p).GetNo();

if(p is Child)
    (p as Child).GetNo();

这篇关于如何使用基类对象调用派生函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆