Adding additional data members to forms
Suppose you want to add a new data member to a form. You want to initialize it in the constructor. What you will add is a constructor with your own name and the extra parameter:
constructor TMyForm.createIt(AOwner: TComponent; someState: boolean);
begin
inherited create(AOwner);
fSomeState := someState;
end;
That is OK. But, what if you want to use the initialized value of fSomeState in FormCreate method? Since create calls FormCreate, what you will get is the uninitialized value. So, for such a requirement, the proper way to do it would be:
constructor TMyForm.createIt(AOwner: TComponent; someState: boolean);
begin
fSomeState := someState;
inherited create(AOwner);
end;
Initially, when I posted some sample code on a newsgroup, someone claimed that this code is wrong, "As the create has not been called, the memory for the object instance is still not created." I was confused. But, then I discovered that what create does is only initialize the allocated memory. So, you can't use any code that references the base class variables before calling create. But, there is no harm if you initialize your own variables for this class. In fact, that is the only way to make sure that FormCreate gets them. Any objections?
本文探讨了在Delphi中如何正确地初始化窗体中的数据成员。通过调整构造函数中的代码顺序,确保在调用基类构造函数之前设置自定义状态变量,从而使FormCreate事件能够获取到已初始化的值。
1073

被折叠的 条评论
为什么被折叠?



