gpt4 book ai didi

Delphi事件处理,如何创建自己的事件

转载 作者:行者123 更新时间:2023-12-03 14:34:55 24 4
gpt4 key购买 nike

我是delphi开发新手。我必须创建一个事件并传递一些属性作为参数。有人可以分享一些演示程序来展示如何从头开始执行此操作。我用谷歌搜索了几乎每个网站,他们都给出了一段代码,但我需要的是一个简单易懂的完整程序。

最佳答案

这是一个简短但完整的控制台应用程序,展示了如何在 Delphi 中创建您自己的事件。包括从类型声明到调用事件的所有内容。阅读代码中的注释以了解发生了什么。

program Project23;

{$APPTYPE CONSOLE}

uses
SysUtils;

type
// Declare an event type. It looks a lot like a normal method declaration except
// it is suffixed by "of object". That "of object" tells Delphi the variable of this
// type needs to be assigned a method of an object, not just any global function
// with the correct signature.
TMyEventTakingAStringParameter = procedure(const aStrParam:string) of object;

// A class that uses the actual event
TMyDummyLoggingClass = class
public
OnLogMsg: TMyEventTakingAStringParameter; // This will hold the "closure", a pointer to
// the method function itself, plus a pointer to the
// object instance it is intended to work on.
procedure LogMsg(const msg:string);
end;

// A class that provides the required string method to be used as a parameter
TMyClassImplementingTheStringMethod = class
public
procedure WriteLine(const Something:string); // Intentionally using different names for
// method and params; Names don't matter, only the
// signature matters.
end;

procedure TMyDummyLoggingClass.LogMsg(const msg: string);
begin
if Assigned(OnLogMsg) then // tests if the event is assigned
OnLogMsg(msg); // calls the event.
end;

procedure TMyClassImplementingTheStringMethod.WriteLine(const Something: string);
begin
// Simple implementation, writing the string to console
Writeln(Something);
end;

var Logging: TMyDummyLoggingClass; // This has the OnLogMsg variable
LoggingProvider: TMyClassImplementingTheStringMethod; // This provides the method we'll assign to OnLogMsg

begin
try
Logging := TMyDummyLoggingClass.Create;
try

// This does nothing, because there's no OnLogMsg assigned.
Logging.LogMsg('Test 1');

LoggingProvider := TMyClassImplementingTheStringMethod.Create;
try
Logging.OnLogMsg := LoggingProvider.WriteLine; // Assign the event
try

// This will indirectly call LoggingProvider.WriteLine, because that's what's
// assigned to Logging.OnLogMsg
Logging.LogMsg('Test 2');

finally Logging.OnLogMsg := nil; // Since the assigned event includes a pointer to both
// the method itself and to the instance of LoggingProvider,
// we need to make sure the event doesn't out-live the LoggingProvider
end;
finally LoggingProvider.Free;
end;
finally Logging.Free;
end;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
end.

关于Delphi事件处理,如何创建自己的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5786595/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com