如何在C#中实现虚拟和重写机制一直是程序员们讨论的热门话题......但在谷歌上搜索半个小时后,我仍然找不到以下问题的答案:
使用简单的代码:
使用简单的代码:
public class BaseClass
{
public virtual SayNo() { return "NO!!!"; }
}
public class SecondClass: BaseClass
{
public override SayNo() { return "No."; }
}
public class ThirdClass: SecondClass
{
public override SayNo() { return "No..."; }
}
class Program
{
static void Main()
{
ThirdClass thirdclass = new ThirdClass();
string a = thirdclass.SayNo(); // this would return "No..."
// Question:
// Is there a way, not using the "new" keyword and/or the "hide"
// mechansim (i.e. not modifying the 3 classes above), can we somehow return
// a string from the SecondClass or even the BaseClass only using the
// variable "third"?
// I know the lines below won't get me to "NO!!!"
BaseClass bc = (BaseClass)thirdclass;
string b = bc.SayNo(); // this gives me "No..." but how to I get to "NO!!!"?
}
}
我认为,如果不修改三个类的方法签名,就无法仅使用最终派生类的实例来访问基类或中间派生类的方法。但是我想确认并加强我的理解......
谢谢。