“此"在从基类派生类的对象上调用时的关键字类型 [英] "this" keyword type when called on an object of derived class from base class
问题描述
如果我有这样的东西:
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";
}
}
并使用以下代码对其进行调用,
and use the following code to call it,
Derived v= new Derived();
v.Write(); // prints Base
然后调用基类的Name
方法.但是Write
方法中this
关键字的实际类型是什么?如果是Derived
类型(因为程序控件在Write
方法中输入第一个if块),则它正在调用基本的Name
方法,为什么显式强制转换(Derived)this
将调用更改为派生类的Name
方法?
then the Name
method of base class gets called. but what would be the actual type of this
keyword in the Write
method? if that is of Derived
type(as the Program control enters the first if block in Write
method) then it is calling the base Name
method, and why does the explicit casting,(Derived)this
, change the call to the Name
method of derived class?
推荐答案
this
将始终为派生类类型.
this
will always be of the derived class type.
之所以在调用this.Name();
中调用基类Name()
方法的原因是因为Name
没有定义为虚拟方法,因此当编译器对实际类型一无所知时,它将在编译时被链接此时它将具有this
的值.
The reason why in the call this.Name();
calls the base class Name()
method is because Name
is not defined as a virtual method, thus it is being linked in compile time when the compiler knows nothing about the actual type of this
that it will have at this point.
关于以上代码的另一条注释.通常,在产品代码中,显式地引用Base类的Derived类确实是一种不好的做法,因为它违反了OOP原则之一,即,Base类不应该知道继承该类的类.但是,假设上面的代码仅用于C ++研究,那当然可以.
One more note regarding the code above. Generally in product code referring to a Derived class from the Base class explicitly is really a bad practice as it breaks one of the OOP principles that the Base class should not be aware about the classes which inherit it. However, assuming that the code above was just used for C++ investigation then this is of course ok.
这篇关于“此"在从基类派生类的对象上调用时的关键字类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!