Both on-line help and the printed Object Pascal manual state that
class reference types can be used on the right-hand side of an AS
operator to typecast an object at runtime ... but my attempts won't
compile:
TMyObject = class(TPersistent)
TMyObjectRef= class of TMyObject
TMyObject1 = class(TMyObject)
TMyObject2 = class(TMyObject)
etc.
var
MyObjectRef:TMyObjectRef
MyObject:TMyObject
..
MyObjectRef:=TMyObject1;
MyObject:=MyObjectRef.create works fine, ie polymorphic construction;
IS operations work ok too - BUT
With MyObject as MyObjectRef do won't compile - gives the error record
or object expected.
Can someone explain to me what sort of bone-headed mistake I'm making?
Or perhaps the help is wrong, and you can't do this ... ??
I want to get at properties added to some of the descendent classes but absent
from the original, and this seemed an elegant way to do it.
Thanks,
David
--
Ray Lischner, Tempest Software, Inc., Corvallis, Oregon, USA
Author of Secrets of Delphi 2 (http://www.tempest-sw.com/secrets/)
Not certain about this: have you tried "With MyObject as TMyObjectRef"?
MyObjectRef is not a class reference, it's a variable... Seems like if you're
using a variable there you'd want a variable with _value_ equal to
TMyObjectRef, and TMyObjectRef is not the value of MyObjectRef, it's
the type of MyObjectRef (???????)
I think so: Not sure what you're trying to do. If you do this:
type
TMyObject = class(TPersistent)
procedure Hmm; virtual; abstract;
end;
TMyObjectRef= class of TMyObject;
TMyObject1 = class(TMyObject)
procedure Hmm; override;
end;
TMyObject2 = class(TMyObject)
procedure Hmm; override;
end;
procedure TMyObject1.Hmm;
begin
showmessage('1');
end;
procedure TMyObject2.Hmm;
begin
showmessage('2');
end;
then either of the following does what I expect:
procedure TForm1.Button1Click(Sender: TObject);
var
MyObjectRef:TMyObjectRef ;
MyObject:TMyObject1 ;
begin
myObject:= TMyObject1.create;
MyObjectRef:= TMyObject1;
With MyObject as MyObjectRef do
begin
Hmm;
Free;
end;
end;
OR
procedure TForm1.Button1Click(Sender: TObject);
var
// MyObjectRef:TMyObjectRef ;
MyObject:TMyObject1 ;
begin
myObject:= TMyObject1.create;
// MyObjectRef:= TMyObject1;
With MyObject as TMyObjectRef do
begin
Hmm;
Free;
end;
end;
--
David Ullrich
?his ?s ?avid ?llrich's ?ig ?ile
(Someone undeleted it for me...)
Ray has it right in another post. The reason David's
examples work is that the compiler optimizes away
the as-statements completly.
MyObject is declared as TMyObject1 which is a
descendant of TMyObject. So MyObject will always
be compatible with the TMyObjectRef class reference.
In both cases the code is compiled as:
procedure TForm1.Button1Click(Sender: TObject);
var
MyObject:TMyObject1 ;
begin
myObject:= TMyObject1.create;
With MyObject do
begin
Hmm;
Free;
end;
end;
--
Hallvard Vassbotn
Falcon R&D
Reuters Norge AS