Pointer to Self, how?
type
TMyClass = class
type
PMyClass = ^TMyClass;
TMyEvent = procedure(Sender: PmyClass) of object;
public
FTest: TMyEvent;
procedure Test;
end;
procedure TMyClass.Test;
begin
FTes开发者_开发百科t(@Self); //error!
end;
How do I do it?
What in the world are you trying to do? Of course you cannot call FTest
since you haven't assigned any TMyEvent
to it yet! And are PMyClass
and TMyEvent
really supposed to be parts of TMyClass
?
At least this works perfectly:
type
PMyClass = ^TMyClass;
TMyClass = class;
TMyEvent = procedure(Sender: PMyClass) of object;
TMyClass = class
private
FEvent: TMyEvent;
FSomeValue: string;
public
property OnSomething: TMyEvent read FEvent write FEvent;
property SomeValue: string read FSomeValue write FSomeValue;
procedure Test;
end;
TSomeOtherClass = class
public
class procedure MyEvent(Sender: PMyClass);
end;
...
procedure TForm6.FormCreate(Sender: TObject);
var
o: TMyClass;
begin
o := TMyClass.Create;
o.SomeValue := 'This is a test.';
o.OnSomething := TSomeOtherClass.MyEvent;
o.Test;
end;
{ TMyClass }
procedure TMyClass.Test;
begin
FEvent(@Self);
end;
{ TSomeOtherClass }
class procedure TSomeOtherClass.MyEvent(Sender: PMyClass);
begin
ShowMessage(TMyClass(Sender^).SomeValue);
end;
Of course, you can also have the TMyEvent
in the same object:
type
TMyClass = class
private type
PMyClass = ^TMyClass;
TMyEvent = procedure(Sender: PMyClass) of object;
private
FEvent: TMyEvent;
FSomeValue: string;
public
procedure TheEventHandler(Sender: PMyClass);
property OnSomething: TMyEvent read FEvent write FEvent;
property SomeValue: string read FSomeValue write FSomeValue;
procedure Test;
end;
...
procedure TForm6.FormCreate(Sender: TObject);
var
o: TMyClass;
begin
o := TMyClass.Create;
o.SomeValue := 'This is a test.';
o.OnSomething := o.TheEventHandler;
o.Test;
end;
{ TMyClass }
procedure TMyClass.Test;
begin
FEvent(@Self);
end;
procedure TMyClass.TheEventHandler(Sender: PMyClass);
begin
ShowMessage(TMyClass(Sender^).SomeValue);
end;
精彩评论