如果我有这样的事情:
class Base
{
public void Write()
{
if (this is Derived)
{
this.Name();//calls Name Method of Base class i.e. prints Base
((Derived)this).Name();//calls Derived Method i.e prints Derived
}
else
{
this.Name();
}
}
public void Name()
{
return "Base";
}
}
class Derived : Base
{
public new void Name()
{
return "Derived";
}
}
并使用以下代码来调用它,
Derived v= new Derived();
v.Write(); // prints Base
那么Name
基类的方法被调用。但实际类型是什么this
中的关键字Write
方法?如果那是Derived
类型(当程序控制进入第一个 if 块时Write
方法)然后它调用基类Name
方法,以及为什么显式转换,(Derived)this
,将调用更改为Name
派生类的方法?
this
将始终是派生类类型。
原因在通话中this.Name();
调用基类Name()
方法是因为Name
没有定义为虚拟方法,因此当编译器对实际类型一无所知时,它是在编译时链接的this
此时它将会有。
关于上面的代码还有一个注释。一般来说,在产品代码中显式引用基类的派生类确实是一种不好的做法,因为它违反了 OOP 原则之一,即基类不应该知道继承它的类。然而,假设上面的代码只是用于 C++ 研究,那么这当然没问题。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)