Method Call and Prank

I have 3 classes inheriting another class called ParentClass , and each of 3 has the following code inside

 public void DrawBackground(Graphics e, Rectangle rect) { e.FillRectangle(Brushes.Red, rect); } 

In my main form, I have a variable like ParentClass PClass = new OneOfTheThreeClasses

How can I call the DrawBAckground method of these classes using this variable from my paint paint event?

+5
source share
1 answer

Create an abstract or virtual method on ParentClass . Something like that:

 public virtual void DrawBackground(Graphics e, Rectangle rect) { // do nothing } 

Then, in child classes, override this method:

 public override void DrawBackground(Graphics e, Rectangle rect) { e.FillRectangle(Brushes.Red, rect); } 

The idea is that a ParentClass needs to define the operations that can be performed on it or any polymorphic version of it (for example, a child type). It does not have to provide an implementation (and the definition may be abstract or virtual depending on how the ParentClass itself ParentClass implemented and used), but it needs to “know” the method in some way in order to be able to call it on the ParentClass instance.

+4
source

All Articles