1

I'm wanting to implement some logging functions in a class I have here. Basically, my thought is to create a TStringList within the class which contains the log. I can do this without any trouble, but my question is how to expose it outside of the class in a way that a control (TMemo or TListBox) can dynamically show the contents if the containing form is present. I could make a direct association to the control within the class, but I'm wanting to keep the class discreet from the form code itself, and create a procedure in the class which makes this association.

Basically, if I have LogFile: TStringList in my class, how do I make it so adding a line there makes it show up in a TMemo from a form that is separate from the class?

4

1 回答 1

1

让表单在您的类中注册一个回调事件。

如果在将项目添加到列表时分配了此事件,请使用回调发送字符串。

Type
  TMyCallback = procedure(const aLogStr: String) of object;

  TMyClass = Class
    private
      FCallback : TMyCallback;
      FLogFile : TStringList;
      procedure SetCallback(ACallback: TMyCallback);
    public
      property Callback : TMyCallback write SetCallback;
  end;

...
// Update FLogFile
FLogFile.Items.Add(SomeText);
if Assigned(FCallback) then
  FCallBack(SomeText);
...

在您的表单类中:

Type
  TMyForm = Class(TForm)
    private
      procedure IncomingLogString(const AStr: String);
  end;

procedure TMyForm.IncomingLogString(const AStr: String);
begin
  MyMemo.Lines.Add(AStr);
end;

...
// Register callback
FMyClass.Callback := Self.IncomingLogString;

现在,您TMyClass与表单的任何依赖脱钩了。

于 2013-10-07T22:20:47.663 回答