Rzutowanie, przysłanianie metod

0

Cześć. Nie bardzo rozumiem dlaczego mimo rzutowania na inne klasy otrzymujemy ten sam wynik we wszystkich trzech wywołaniach. Prosiłbym o krótkie wyjaśnienie. Dziękuje.

class A { public virtual string g() { return "A.g"; } }
class B:A { public override string g() { return "B.g"; } }
class C:B { public override string g() { return "C.g"; } }

C c = new C;
B b = c;
A a = b;

Console.WriteLine(a.g() + " - " + b.g() + " - " + c.g()); // C.g - C.g - C.g
4

Na tym polega polimorfizm.

Wywołując metodę g na obiekcie, wywoływana jest faktyczna wersja tej metody klasy dla której faktycznie należy ten obiekt, a nie taki w jaki ją sobie traktujemy w danej chwili. Z drugiej strony każdy obiekt klasy C będzie bezproblemowo pasował do parametrów oczekujących klasy bazowej (A lub B).

At run-time, when client code calls the method, the CLR looks up the run-time type of the object, and invokes that override of the virtual method. Thus in your source code you can call a method on a base class, and cause a derived class's version of the method to be executed.

https://docs.microsoft.com/pl-pl/dotnet/articles/csharp/programming-guide/classes-and-structs/polymorphism

0

Chodziło ci o coś takiego:


class A { public string g() { return "A.g"; } }
class B:A { public new string g() { return "B.g"; } }
class C:B { public new string g() { return "C.g"; } }
 
C c = new C();
B b = c;
A a = b;
 
Console.WriteLine(a.g() + " - " + b.g() + " - " + c.g()); // A.g - B.g - C.g

1 użytkowników online, w tym zalogowanych: 0, gości: 1