【发布时间】:2017-09-04 06:04:57
【问题描述】:
是这样的:
3 involucated:一个myComponent组件,一个祖先表单和一个子表单:(已编辑)
我的组件:
unit Component1;
interface
uses
System.SysUtils, System.Classes, Vcl.Dialogs;
type
TMyComponent = class(TComponent)
private
{ Private declarations }
procedure Something(i: Integer);
protected
{ Protected declarations }
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
published
{ Published declarations }
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Samples', [TMyComponent]);
end;
{ TMyComponent }
constructor TMyComponent.Create(AOwner: TComponent);
var
i: integer;
begin
inherited Create(AOwner);
if AOwner.ComponentCount > 0 then
for i := 0 to AOwner.ComponentCount -1 do
Something(i);
end;
procedure TMyComponent.Something(i: Integer);
var
txt: string;
begin
txt := Format('Owner Name is %s, Owner Class is %s, ComponentCount is %d,'+
'myIndex is %d, My name is %s, my class is %s',
[Owner.Name, Owner.ClassName, Owner.ComponentCount, i, Owner.Components[i].Name,
Owner.Components[i].ClassName]);
ShowMessage('Hello '+txt);
end;
end.
祖先形态:
unit Ancestor;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Component1;
type
TmyAncestor = class(TForm)
MyComponent1: TMyComponent;
private
{ Private declarations }
public
{ Public declarations }
end;
var
myAncestor: TmyAncestor;
implementation
{$R *.dfm}
end.
子窗体:
unit TheChild;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Ancestor, Vcl.StdCtrls, Component1;
type
TmyChild = class(TmyAncestor)
edt1: TEdit;
private
{ Private declarations }
public
{ Public declarations }
end;
var
myChild: TmyChild;
implementation
{$R *.dfm}
end.
dpr:
program InheritanceTest;
uses
Vcl.Forms,
Ancestor in 'Ancestor.pas' {myAncestor},
TheChild in 'TheChild.pas' {myChild};
{$R *.res}
begin
Application.Initialize;
Application.MainFormOnTaskbar := True;
Application.CreateForm(TmyChild, myChild);
Application.Run;
end.
子 Form 从祖先 Form 继承 myComponent。
创建时,子窗体会触发TMyComponent.Create() 构造函数,但AOwner.ComponentCount 看到的是祖先ComponentCount 而不是子窗体的ComponentCount。
消息(来自myComponent.Something() 方法)显示:
"Hello Owner Name 是 myAncestor,Owner class 是 TMyChild,ComponentCount 是 1,myIdex 是 0,我的 name 是,我的 class 是 TMyComponent"
组件在子窗体中看不到edt1组件!!!
如何查看正确的 ComponentCount?
【问题讨论】:
-
我可以附加文件吗?
-
不要附加文件。创建minimal reproducible example 并将其编辑到问题中
标签: inheritance components delphi-xe8