inheritance - Different behaviour of method overloading in C# -
I was going through #Brainteasers () and came across a question: What should be the output of this code?
Class Base {Public Virtual Zero Foo (int x) {Console.WriteLine ("Base.Foo (int)"); }} Category derived: base {public override zero foo (int x) {Console.WriteLine ("derived.Foo (int)"); } Public Zero Foo (Object O) {Console.WriteLine ("Derived.Foo (Object)"); }} Class Test {Static Wide Men ()} {Delivered D = New Deferred (); Int i = 10; D.Foo (i); // It prints ("derived .foo (object)"}}
But if I change the code for
class {public Zero} int x) {Console.WriteLine ("Derived.Foo (int)"}}} Public Zero Foo (Object O) {Console.WriteLine ("Derived.Foo (object)")}}} Class Program {static void Main (string [] args) {derived d = new derived (); Int i = 10; D.Foo (i); // has been printed. Fu (int) "; console; redkey ();}}
Why do I want to know why the output is changing when we do not make inherent, in these two cases Why are there ways to behave differently?
As I have specified in the page:
Derived.Foo (object) is printed - When selecting surcharges, if there is no consistent derivative method declared in the class, base All the signatures declared in the class are ignored - even if they are odd in the same derivative category!
In other words, the compiler looks at those methods which are the most derived class ( On the basis of the compilation-time type of expression, it is declared fresh and sees that none is applicable. If they are, then it uses the available "best" one if none is applicable, then this Of base Troubles try, and so on. Override method is not considered as being declared in a derivative class.
For more information, Section 7.4.3 and 7.5 of the details of C # 3. See 5.1
Why is this really so specified - I do not know, it is understandable for me that the methods declared in the derivative category are given priority in comparison to those declared in the base class, otherwise you will be given " Brittle base class "problem - By adding a method to the base class, the meaning of the code can change the derived class However, if derived class is the overriding method declared in the base class, then There is clearly aware of, which does not apply to elements of that fragility.
Comments
Post a Comment