C# の仮想およびオーバーライド メカニズムが内部でどのように機能するかというトピックは、プログラマーの間で死に至るまで議論されてきました...しかし、Google で 30 分後、次の質問に対する答えが見つかりません (以下を参照)。
簡単なコードを使用する:
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!!!"? } }
基本クラスまたは中間派生クラスのメソッドに、最も派生したインスタンスを使用するだけでは (3 つのクラスのメソッド シグネチャを変更せずに) 到達できないと思います。しかし、私の理解を確認し、固めたいと思います...
ありがとう。