سؤال

I have an TObject called Target2 that is a pointer to say TLabel and would like to get the property Name from this pointer. Thus I have this

Procedure TGetName()
var
  Item : TLabel;
Begin
  if Target2 is TLabel then
  begin
     Item := Target2;
     if Item.Name := 'SomeName' then
       begin
        ....
       dosomething();
       end;
  end;
end;

But it seem pointless to have Item now become a pointer to a pointer but when I do:

Procedure TGetName()
Begin
  if Target2 is TLabel then
   begin
      if Target2.Name := 'SomeName' then
         begin
          ....
         dosomething();
         end;
    end;
end;

I get errror that name is not a member of Target2. Thus how do I access this without creating another pointer to the pointer Target2?

هل كانت مفيدة؟

المحلول

You just need to cast. If you are prepared to assert the Target2 is a TLabel then use a checked cast:

var
  Lbl: TLabel;
....
Lbl := Target2 as TLabel;

Otherwise check using is and then an unchecked cast is fine:

if Target2 is TLabel then
begin
  Lbl := TLabel(Target2);
  ....

You don't need to destroy Lbl because it is just a reference to an object that is owned by somebody else.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top