为什么在这里访问冲突? [英] Why Access Violation here?
问题描述
我正在尝试在某些Delphi项目中构建自己的类。代码是这样的:
I'm trying to construct my own class in some Delphi Project. The code is like this:
type
TMyClass = class(TObject)
private
hwnMain, hwnChild: HWND;
Buffer, URL: string;
Timer: TTimer;
public
procedure ScanForClass;
end;
var
Form1: TForm1;
TimerAccess: TMyClass;
implementation
procedure TForm1.FormCreate(Sender: TObject);
begin
TimerAccess.ScanForClass;
end;
procedure TMyClass.ScanForClass;
begin
Timer:= TTimer.Create(Application); **here I get Access Violation!!**
Timer.Interval:= 5000;
Timer.Enabled:= true;
为什么会发生访问冲突?
why getting that access violation?
推荐答案
您的代码在使用该类之前不会创建该类的实例。
Your code does not create an instance of the class before using it.
因此它将在此代码中引发访问冲突异常:
So it will raise a access violation Exception in this code:
procedure TForm1.FormCreate(Sender: TObject);
begin
TimerAccess.ScanForClass;
end;
因为TimerAccess仍未初始化(未定义)。
because TimerAccess is still uninitialized (undefined).
在FormCreate中,调用构造函数并将实例分配给变量
in FormCreate, call the constructor and assign the instance to the variable
procedure TForm1.FormCreate(Sender: TObject);
begin
TimerAccess := TMyClass.Create;
TimerAccess.ScanForClass;
end;
在FormDestroy中,调用析构函数进行清理:
in FormDestroy, call the destructor to cleanup:
procedure TForm1.FormDestroy(Sender: TObject);
begin
TimerAccess.Free;
end;
注意:如果有很多TForm1实例,该代码将不起作用,因为变量TimerAccess是全局变量,并且每个Form实例都会在FormCreate中分配一个新的TMyClass实例,从而导致内存泄漏。一种解决方案是使TimerAccess成为Form类的属性(或字段)。
Note: the code will not work if there are many instances of TForm1, because the variable TimerAccess is global, and every Form instance will assign a new instance of TMyClass in FormCreate, thus causing memory leaks. One solution would be to make TimerAccess a property (or field) of the Form class.
这篇关于为什么在这里访问冲突?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!