1

我需要保存一些属性并将其加载到数据库中,但我对此感到困惑。我有一个带有几种方法和一个按钮的表单。button.onclick 事件被分配给表单的方法之一。我需要将分配的方法的名称作为字符串(就像对象检查器“form1.proc1”)并将其保存到数据库中。稍后我需要从数据库中获取方法名称并将 button.onclick 分配给相应表单的方法。这可能吗?

Form1 = class(TForm)
...
procedure proc1(Sender: TObject);
procedure proc2(Sender: TObject);
procedure proc3(Sender: TObject);

Button1.OnClick = readMethodNameFromDatabase; 
...
saveMethodToDatabase(Button1.OnClick);
4

1 回答 1

4

You can obtain a method, given its name, like this:

function TForm1.MethodFromName(const Name: string): TNotifyEvent;
begin
  TMethod(Result).Data := Self;
  TMethod(Result).Code := MethodAddress(Name);
  if TMethod(Result).Code=nil then
    raise Exception.CreateFmt('Count not find method named %s', [Name]);
end;

This is the mechanism that the RTL uses when reading your .dfm files. It relies on the method being published.

You can call it like this:

Button1.OnClick := TNotifyEvent(MethodFromName('Button1Click'));

Naturally you'd substitute a database read in the final code.


As for the second part of your question, you can get the name of an event handler with this code:

MethodName(@Button1.OnClick);
于 2012-09-11T10:40:01.290 回答