![]() |
Delphi-Version: 2010
Need create and call method from many class types
Hello, guys,
So, lets say what I have. I have two classes: - TClass1(TBaseClass) - TClass2(BaseClass) TClass1 and TClass2 extands TBaseClass, both are for different input data types. TClass1/TClass2 has LoadFromStream and SaveToStream. Now, how to create and call methods with names that are common for any class TSomeOtherClass(TClass1/TClass2), like stream procedures? Currently I have: if class = someclass then someclass.loadfromstream else if class = otherclass then otherclass.loadfromstream else if class = yetanotherclass then yetanotherclass.loadfromstream but in future I'll have too many classes to add if statement in few places in few units in program. Could you help with this? |
AW: Need create and call method from many class types
Why not
Delphi-Quellcode:
?
if class is TBaseclass then BaseClass( class).loadfromstream());
|
Re: Need create and call method from many class types
And this will call correct method (someclass.loadfromstream)?
|
AW: Need create and call method from many class types
Yes, if BaseClass is a superclass of class
|
Re: Need create and call method from many class types
What it mean? This is somethink like this (I saw somewhere, but don't know how it working):
Delphi-Quellcode:
TClassOfBase = class of TBaseClass
Delphi-Quellcode:
TBaseClass = class;
TSomeClassA = class(TBaseClass); TSomeClassB = class(TBaseClass); //(TSomeClassA and TSomeClassB) are base for any class I'm working with it). I have TClass1(TSomeClassA), TClass2(TSomeClassB), etc. How it should be done to avoid many thousends if-then-else? Could you explain me, because I don't understand? |
AW: Need create and call method from many class types
Because of the IS-A paradigm each Subclass "is a" Baseclass
if the wanted function/procedure is declared in a superclass ( baseclass->MiddleClass->Class1) it can be called as function/procedure of the superclass. It'S always called the "best matched" function. if the function is implemented in the Baaseclass this function is called, if the implementation is in Class1/Class2 then the corresponding versions are used:
Delphi-Quellcode:
calls Tclass1.AnyFunc()
TBaseClass(class1).AnyFunc()
|
AW: Need create and call method from many class types
If you want to figure out how the "Class of Class" thing works, just try to understand the TPicture.LoadFromFile method, which can be found in the "graphics" unit.
|
AW: Need create and call method from many class types
TBaseClass has to have LoadFromStream as virtual (abstract).
|
Alle Zeitangaben in WEZ +1. Es ist jetzt 01:01 Uhr. |
Powered by vBulletin® Copyright ©2000 - 2025, Jelsoft Enterprises Ltd.
LinkBacks Enabled by vBSEO © 2011, Crawlability, Inc.
Delphi-PRAXiS (c) 2002 - 2023 by Daniel R. Wolf, 2024-2025 by Thomas Breitkreuz