这是我混淆的代码。
class foo
{
public string fname;
public virtual void print()
{
Console.WriteLine("I am the boss i am the virtual");
}
};
class bar : foo
{
public override void print()
{
Console.WriteLine("I am the first derivative");
}
};
class tar : bar
{
public new virtual void print()
{
Console.WriteLine("I am the newly born baby with a new keyword!!!!");
}
};
class jar : tar
{
public override void print()
{
Console.WriteLine("i am created in derivative of tar i.e, jar");
}
};
class Program
{
static void Main(string[] args)
{
foo obj1 = new foo();
obj1.fname = "neha";
foo objtar = new jar(); //here lies the confusion why bar print() is called
objtar.print();
}
}
在此代码中,我使用第 3 级派生类 (jar) 对象和基类 (foo) 调用打印方法。查看输出结果我感到很困惑
I am the first derivative
谁能解释一下背后的原因。我是 c# 的新手,需要帮助....
最佳答案
那是因为您在 foo
的实例上调用了 print
。 new
关键字将仅应用于该类型的类型化实例。
继承规则不再适用,因为 tar.print
是新的
。
这是所有记录在案的行为,您可以在 MSDN 上找到.
所以这将按您的预期工作:
jar objtar = new jar();
objtar.print();
关于c# - 使用 new 关键字中断虚拟调用并再次启动新的虚拟层次结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25140044/