Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > Delphi программирование > Общие вопросы Delphi
Регистрация

Восстановить пароль

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 11.09.2010, 12:42   #1
Roof
Форумчанин
 
Аватар для Roof
 
Регистрация: 01.02.2007
Сообщений: 785
По умолчанию В методе TCollectionItem получить значение поля класса, содержащего TCollection

1) Класс TProtection является наследником TCollectionItem и содержит метод CalcProt.
2) Класс TCollProtection является наследником TCollection, он содержит Items класса TProtection
3) Класс TLand является наследником TCollectionItem и содержит поле класса TCollProtection

Так вот - мне необходимо в методе CalcProt класса TProtection получить доступ к полям клсаа TLand. Сделал, но получается нужно проходить к полям класса TLand через двух владельцев - TCollection и TLand.

Вопрос - можно ли сделать проще?
Вот мой код:
Код:
unit Land;

interface
uses Classes;

type
  TCollProtection = class;
  TLand = class;

  TProtection= class(TCollectionItem)
  private
    FInsekt: real;
    FGerbic: real;
    FFungic: real;
    FProt: real;
    FOwner: TCollProtection;   // для получения владельца
  public
    constructor Create(Collection: TCollection); override;
    destructor Destroy; override;
    procedure CalcProt;  // интересует эта процедура
  published
    property Insekt: real read FInsekt write FInsekt;
    property Gerbic: real read FGerbic write FGerbic;
    property Fungic: real read FFungic write FFungic;
    property Prot: real read FProt;
  end;

  TCollProtection = class(TCollection)
  private
    FGtr: real;
    FOwner: TLand; // для получения владельца
  public
    constructor Create(ItemClass: TCollectionItemClass; AOwner: TLand);
    function GetProtection(index: Integer): TProtection;
    procedure SetProtection(index: Integer; Value: TProtection);
    function Add: TProtection;

    property Items[index: Integer]: TProtection read GetProtection
    write SetProtection; default;
    property Gtr: real read FGtr write FGtr;
  end;

  TLand = class(TCollectionItem)
  private
    FCost: real;
    FPrice: real;
    FCollProtection: TCollProtection;  // вложение
    FArea: real;
    FProductivity: real;
  public

    constructor Create(Collection: TCollection); override;
    destructor Destroy; override;

  published
    property Area: real read FArea write FArea;
    property Productivity: real read FProductivity write FProductivity;
    property Cost: real read FCost;
    property Price: real read FPrice write FPrice;
    property CollProtection: TCollProtection read FCollProtection
      write FCollProtection;
  end;

  TCollLand = class(TCollection)
  public

    function GetLand(index: Integer): TLand;
    procedure SetLand(index: Integer; Value: TLand);
    function Add: TLand;
    property Items[index: Integer]: TLand read GetLand
    write SetLand; default;
  end;
  
  TAcLand = class(TComponent)
  private
    name: string;
    FCollLand: TCollLand;

  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;

  published
    property CollLand: TCollLand read FCollLand write FCollLand;

  end;

implementation

{ TLand }

constructor TLand.Create(Collection: TCollection);
begin
  inherited;
  FCollProtection := TCollProtection.Create(TProtection, Self);
end;

destructor TLand.Destroy;
begin
  FCollProtection.Free;
  inherited;
end;

{ TCollLand }

function TCollLand.Add: TLand;
begin
  Result := TLand(inherited Add);
end;


function TCollLand.GetLand(index: Integer): TLand;
begin
  Result := TLand(inherited Items[index]);
end;

procedure TCollLand.SetLand(index: Integer; Value: TLand);
begin
  Items[index].Assign(Value);
end;

{ TAcLand }

constructor TAcLand.Create(AOwner: TComponent);
begin
  inherited;
  FCollLand := TCollLand.Create(TLand);
end;

destructor TAcLand.Destroy;
begin
  FCollLand.Free;
  inherited;
end;

{ TProtection }

procedure TProtection.CalcProt;
begin
  FOwner.FGtr := 444;
  FProt := (FInsekt + FGerbic + FFungic + FOwner.FOwner.FArea); // проходим через двух владельцев
end;

constructor TProtection.Create(Collection: TCollection);
begin
  inherited;
  FOwner := Collection as TCollProtection;
end;

destructor TProtection.Destroy;
begin

  inherited;
end;

{ TCollProtection }

function TCollProtection.Add: TProtection;
begin
  Result := TProtection(inherited Add);
end;


constructor TCollProtection.Create(ItemClass: TCollectionItemClass; AOwner: TLand);
begin
  inherited Create(ItemClass);
  FOwner := AOwner;
end;

function TCollProtection.GetProtection(index: Integer): TProtection;
begin
  Result := TProtection(inherited Items[index]);
end;

procedure TCollProtection.SetProtection(index: Integer; Value: TProtection);
begin
  Items[index].Assign(Value);
end;


end.
Изо всей благодати
В руках крепко сжатых
Я донесу только капли
Roof вне форума Ответить с цитированием
Старый 12.09.2010, 01:33   #2
mutabor
Телепат с дипломом
Старожил
 
Аватар для mutabor
 
Регистрация: 10.06.2007
Сообщений: 4,929
По умолчанию

А что тебя смущает? Получаешь доступ через два объекта, ну и что? Это не много.
Если тебя смущает, что непонятно потом будет, напиши комментарий поясняющий.
The future is not a tablet with a 9" screen no more than the future was a 9" black & white screen in a box. It’s the paradigm that survives. (Kroc Camen)
Проверь себя! Онлайн тестирование | Мой блог
mutabor вне форума Ответить с цитированием
Старый 12.09.2010, 01:55   #3
Roof
Форумчанин
 
Аватар для Roof
 
Регистрация: 01.02.2007
Сообщений: 785
По умолчанию

Меня не смущает, а комментарии поясняющие у меня есть у каждого нового поля и каждого нового метода, иначе запутываюсь. Я пытаюсь выйти на рациональные решения в больших (на мой взгляд) объемах данных потому и спрашиваю правильно ли я делаю, или можно все проще. За ответ Спасибо.
Изо всей благодати
В руках крепко сжатых
Я донесу только капли
Roof вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц



Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
получить значение поля другого класса Roof Общие вопросы Delphi 11 10.09.2010 15:10
получить данные поля исходя из lookup-поля malayka Помощь студентам 0 21.04.2010 21:19
как получить значение поля грид на основе значения другого lookUp поля malayka БД в Delphi 0 21.04.2010 19:06
Поля класса xell29 Общие вопросы Delphi 8 18.06.2009 17:10
Как в С++ вывести(записать ) информацию в файл, когда инфа находится в методе класса? Artur_cod Общие вопросы C/C++ 1 06.05.2007 00:34