私がこのようなものを持っている場合:
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