关于调用
本帖最后由 kingisw 于 2013-08-16 13:54:16 编辑
function func1():string;
function func2():string;
function func3():string;
TMyThread = class(TThread)
end;
implementation
function func1():string;
var
myThread :TMyThread;
begin
//问题在这里,如何能动态的在线程中执行 func2 或 func3 ???
end;
[解决办法]
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TFun = function():string;
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
TMyThread = class(TThread)
f1: TFun;
end;
function func1():string;
function func2():string;
function func3():string;
var
Form1: TForm1;
implementation
{$R *.dfm}
function func1():string;
begin
result := 'this is func1';
end;
function func2():string;
begin
result := 'this is func2';
end;
function func3():string;
begin
result := 'this is func3';
end;
procedure TForm1.Button1Click(Sender: TObject);
var
myThread :TMyThread;
begin
myThread := TMyThread.Create(true);
myThread.f1 := func1;
showmessage(myThread.f1);
myThread.f1 := func2;
showmessage(myThread.f1);
myThread.Free;
end;
end.
------解决方案--------------------
你定义一个过程类型就可以解决你的问题了,若想引用一个实例对象的方法(参
考Classes and objects),你需要在过程类型的名称后面加上of object。比如
type
TMethod = procedure of object;
TNotifyEvent = procedure(Sender: TObject) of object;
这些类型表示方法指针。方法指针实际上是一对指针:第一个存储方法的地址,第二个存储方法所属的
对象的引用。