透過原始碼學習TComponent類的機制(1) (轉)

amyz發表於2007-08-15
透過原始碼學習TComponent類的機制(1) (轉)[@more@]

  學習最好的方法是看DELPHI的VCL原始碼愛看他的機制本文就類TComponent的原始碼來看他的機制.
{ TComponent }
constructor TComponent.Create(AOwner: TComponent);
begin
  FComponentStyle := [csInheritable];
  if AOwner <> nil then AOwner.InsertComponent(Self);
end;

procedure TComponent.InsertComponent(AComponent: TComponent);
begin
  AComponent.ValidateContainer(Self);
  ValidateRename(AComponent, ', AComponent.FName);//看是否有重名的如果有則發異常
  Insert(AComponent);//在自己的子列表里加入AComponent的引用
  AComponent.SetReference(True);
  if csDesigning in ComponentState then
  AComponent.SetDesigning(True);
  Notification(AComponent, opInsert);//給自己發一個通知訊息
end;

procedure TComponent.ValidateRename(AComponent: TComponent;
  const CurName, NewName: string);
begin
  if (AComponent <> nil) and not SameText(CurName, NewName) and
  (AComponent.Owner = Self) and (FindComponent(NewName) <> nil) then
  raise EComponentError.CreateRemt(@SDuplicateName, [NewName]);
  if (csDesigning in ComponentState) and (Owner <> nil) then
  Owner.ValidateRename(AComponent, CurName, NewName);//遞迴查是否有重名的元件
end;

procedure TComponent.ValidateContainer(AComponent: TComponent);
begin
  AComponent.ValidateInsert(Self);
end;

procedure TComponent.ValidateInsert(AComponent: TComponent);
begin
end;

procedure TComponent.Insert(AComponent: TComponent);//我們可以看到他的子元件的引用是用TLIST來儲存的
begin
  if FComponents = nil then FComponents := TList.Create;
  FComponents.Add(AComponent);
  AComponent.FOwner := Self;//給剛剛加上的主件賦上擁有者屬性
end;

destructor TComponent.Destroy; 以看到每一個元件都維護一個FFREENOTIFILES的列表
begin
  Destroying;
  if FFreeNotifies <> nil then
  begin
  while Assigned(FFreeNotifies) and (FFreeNotifies.Count > 0) do
  TComponent(FFreeNotifies[FFreeNotifies.Count - 1]).Notification(Self, opRemove);
  FreeAndNil(FFreeNotifies);//如果自己析構的時候,對自己FFREENOTIFILES裡面引用的物件呼叫Notification,把自己析構造的事件告訴他們
  end;
  DestroyComponents;
  if FOwner <> nil then FOwner.RemoveComponent(Self);
  inherited Destroy;
end;

procedure TComponent.FreeNotification(AComponent: TComponent);//透過這個過程可以證實FFREENOTIFILES是一個列表這個列表維護自己析構的時候給那些物件通知
begin
  if (Owner = nil) or (AComponent.Owner <> Owner) then
  begin
  // Never acquire a reference to a component that is being deleted.
  assert(not (csDestroying in (ComponentState + AComponent.ComponentState)));
  if not Assigned(FFreeNotifies) then FFreeNotifies := TList.Create;
  if FFreeNotifies.IndexOf(AComponent) < 0 then
  begin
  FFreeNotifies.Add(AComponent);
  AComponent.FreeNotification(Self);
  end;
  end;
  Include(FComponentState, csFreeNotification);
end;


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/10752019/viewspace-957817/,如需轉載,請註明出處,否則將追究法律責任。

相關文章