На главную Наши проекты:
Журнал   ·   Discuz!ML   ·   Wiki   ·   DRKB   ·   Помощь проекту
ПРАВИЛА FAQ Помощь Участники Календарь Избранное RSS
msm.ru
! ПРАВИЛА РАЗДЕЛА · FAQ раздела Delphi · Книги по Delphi
Обязательно выделяйте текст программы тегом [сode=pas] ... [/сode]. Для этого используйте кнопку [code=pas] в форме ответа или комбобокс, если нужно вставить код на языке, отличном от Дельфи/Паскаля.

Этот раздел предназначен для вопросов, посвященных разработке компонентов, а также для тестирования собственных бесплатных компонентов с открытым исходным кодом.

Здесь запрещается:
1. Размещать ссылки на какие-либо коммерческие компоненты, реализующие требуемую функциональность.
2. Обсуждать и тестировать коммерческие компоненты или компоненты с закрытым кодом.
3. Давать ссылки на сайты с исходным кодом компонентов. Все тестируемые исходные коды должы быть размещены на сайте ИСХОДНИКИ.RU.
Модераторы: Rouse_, DimaBr
  
> Как правильно выводить значения свойств через массив. , Как правильно выводить значения свойств через массив.
    Добрый вечер!

    Создан компонент по такой схеме:

    ExpandedWrap disabled
      unit MyComponent;
       
      interface
       
      uses Windows, Messages, SysUtils, Variants, Classes, Controls;
       
      type
        TMyComponent = class(TComponent)
        private
          fIndex : Integer;
          fh1: Double;
          fh2 : Double;
          fh3 : Double;
          fh4 : Double;
          fh5 : Double;
          fh6 : Double;
          fh7 : Double;
          function GetIndex : Integer;
          procedure SetIndex(Value : Integer);
          function GetElement(Index : Integer): Double;
          function GetDataElement(Index : Integer): Double;
        protected
          //...............
        public
          constructor Create(AOwner: TComponent);override;
          destructor Destroy;override;
          function Oma(U : Integer): Double;
          procedure Assign(Source: TPersistent);
          property Element[Index : Integer] : Double read GetElement;
        published
          property IndexElement : Integer read GetIndex write SetIndex;
          property h1 : Double index 0 read GetDataElement write fh1;
          property h2 : Double index 1 read GetDataElement write fh2;
          property h3 : Double index 2 read GetDataElement write fh3;
          property h4 : Double index 3 read GetDataElement write fh4;
          property h5 : Double index 4 read GetDataElement write fh5;
          property h6 : Double index 5 read GetDataElement write fh6;
          property h7 : Double index 6 read GetDataElement write fh7;
        end;
       
        procedure Register;
       
      implementation
       
      { TMyComponent }
       
      function TMyComponent.Oma(U : Integer): Double;
      begin
        Result := 100/Random(U);
      end;
       
      procedure TMyComponent.Assign(Source: TPersistent);
      begin
        if Source is TMyComponent then
        begin
          fh1 := TMyComponent(Source).h1;
          fh2 := TMyComponent(Source).h2;
          fh3 := TMyComponent(Source).h3;
          fh4 := TMyComponent(Source).h4;
          fh5 := TMyComponent(Source).h5;
          fh6 := TMyComponent(Source).h6;
          fh7 := TMyComponent(Source).h7;
       end
       else inherited Assign(Source);
      end;
       
      function TMyComponent.GetElement(Index : Integer): Double;
      var
        i : integer;
      begin
        Result := 0;
        for i:= 0 to 6 do
        begin
        if (Index<=0) or (Index>7) then
         raise Exception.Create( 'Номер в массиве должен быть числом от 0 до 6')
        else
          Result := i;
        end;
      end;
       
      function TMyComponent.GetDataElement(Index : Integer): Double;
      begin
        Result := 0;
        case Index of
          0 : Result := Oma(fIndex);
          1 : Result := Oma(fIndex);
          2 : Result := Oma(fIndex);
          3 : Result := Oma(fIndex);
          4 : Result := Oma(fIndex);
          5 : Result := Oma(fIndex);
          6 : Result := Oma(fIndex);
        end;
      end;
       
      constructor TMyComponent.Create(AOwner: TComponent);
      begin
        inherited;
      end;
       
      destructor TMyComponent.Destroy;
      begin
        inherited;
      end;
       
      function TMyComponent.GetIndex : Integer;
      begin
        Result := FIndex;
      end;
       
      procedure TMyComponent.SetIndex(Value : Integer);
      begin
        if Value<>fIndex then
          fIndex := Value;
      end;
       
      procedure Register;
      begin
        RegisterComponents('test', [TMyComponent]);
      end;
       
      end.


    Вопрос: как можно и дизайнтайме показать значения свойств property h1, property h2, property h3, property h4, property h5, property h6, property h7 в Инстпекторе Объектов и в realtime выводить значения этих свойств не по одному, а через массив, используя конструкцию for i :=0 to High(массив) do с доступом к каждому из property h1, property h2, property h3, property h4, property h5, property h6, property h7.

    Спасибо.
    Сообщение отредактировано: SkAndriy -
      Цитата SkAndriy @
      как можно и дизайнтайме показать значения свойств property h1, property h2, property h3, property h4, property h5, property h6, property h7 в Инстпекторе Объектов

      разве при объявлении в секции published они уже не должны отображаться?
      Цитата SkAndriy @
      в realtime выводить значения этих свойств не по одному, а через массив, используя конструкцию for i :=0 to High(массив) do с доступом к каждому из property h1, property h2, property h3, property h4, property h5, property h6, property h7

      можно открыть функцию GetDataElement, и, если кол-во h всегда постоянно завести константу в классе, для которой использовать цикл for:
      ExpandedWrap disabled
        for i := 1 to H_COUNT do
          Showmessage(FloatToStr(GetDataElement(i-1)));

      Хотя в таком случае вся структура компонента кажется странноватой. <_<
      Сообщение отредактировано: Keeper89 -
        Да они видны, просто мне нужно их вывести в виде массива. Спасибо.
          Поробовал вот такую конструкцию, но она не работает тоже:

          ExpandedWrap disabled
            unit MyComponent;
             
            interface
             
            uses Windows, Messages, SysUtils, Variants, Classes, Controls;
             
            type
              TMyComponent = class(TComponent)
              private
                fIndex : Integer;
                fh1: Double;
                fh2 : Double;
                fh3 : Double;
                fh4 : Double;
                fh5 : Double;
                fh6 : Double;
                fh7 : Double;
               function  GetMyFunc(Index: Integer): Double;
              protected
                //...............
              public
                constructor Create(AOwner: TComponent);override;
                destructor Destroy;override;
                procedure Assign(Source: TPersistent);
                property MyArray[Index: Integer] : Double read GetMyFunc;
              published
                property h1 : Double index 0 read GetMyFunct write fh1;
                property h2 : Double index 1 read GetMyFunc write fh2;
                property h3 : Double index 2 read GetMyFunc write fh3;
                property h4 : Double index 3 read GetMyFunc write fh4;
                property h5 : Double index 4 read GetMyFunc write fh5;
                property h6 : Double index 5 read GetMyFunc write fh6;
                property h7 : Double index 6 read GetMyFunc write fh7;
              end;
             
              procedure Register;
             
            implementation
             
            { TMyComponent }
             
            function TMyComponent.Oma(U : Integer): Double;
            begin
              Result := 100/Random(U);
            end;
             
            procedure TMyComponent.Assign(Source: TPersistent);
            begin
              if Source is TMyComponent then
              begin
                fh1 := TMyComponent(Source).h1;
                fh2 := TMyComponent(Source).h2;
                fh3 := TMyComponent(Source).h3;
                fh4 := TMyComponent(Source).h4;
                fh5 := TMyComponent(Source).h5;
                fh6 := TMyComponent(Source).h6;
                fh7 := TMyComponent(Source).h7;
             end
             else inherited Assign(Source);
            end;
             
            function TMyComponent.GetMyFunc(Index : Integer): Double;
            begin
              if (Index >= 0) and (Index <= 6) then
               case Index of
                0 : Result := Oma(fIndex);
                1 : Result := Oma(fIndex);
                2 : Result := Oma(fIndex);
                3 : Result := Oma(fIndex);
                4 : Result := Oma(fIndex);
                5 : Result := Oma(fIndex);
                6 : Result := Oma(fIndex);
              end
              else
                Result := -1;
            end;
             
            constructor TMyComponent.Create(AOwner: TComponent);
            begin
              inherited;
            end;
             
            destructor TMyComponent.Destroy;
            begin
              inherited;
            end;
             
            procedure Register;
            begin
              RegisterComponents('test', [TMyComponent]);
            end;
             
            end.


          Подскажите где ошибка?

          Спасибо
            Я не совсем Вас понимаю, покажете картинку-пример, то такое "вывести в виде массива"?
              Задача следующая:

              В realtime значения полей h1-h7 выводить не по отдельности, например, пременная1 := MyComponent1.h1 и так далее пременная7 := MyComponent1.h7, а через некий массив:

              for i := 0 to 6 do
              myarray[i] := MyComponent1.arrayvalueaofproperties1_7[i]

              Теперь понятно показал?

              Спасибо
              Сообщение отредактировано: SkAndriy -
                ExpandedWrap disabled
                  property CArray[index: integer]: Double read GetArray write SetArray;
                Сообщение отредактировано: Демо -
                  Это понятно, а как CArray поймет, что нужно ему выводить? Что именно значения полей h1-h7? Вот в чем вопрос. Спасибо
                  Сообщение отредактировано: SkAndriy -
                    Добавь эту строку в секцию public и нажми Ctrl-Shift-C...

                    Добавлено
                    Так массив или поля всё-таки?

                    Добавлено
                    Изврат какой-то.

                    ExpandedWrap disabled
                      case index of
                        0: Result := h0;
                        1: Result := h2;
                        ...
                        7:  Result := h7;
                      else Result := -1;
                      end;
                      Цитата Демо @
                      Так массив или поля всё-таки?
                      Изврат какой-то.

                      собственно и я о чем, в одном месте хочется поля, в другом - массив.

                      Судя по задаче не надо никаких h1, h2,..,h7, а нужен массив h.:
                      ExpandedWrap disabled
                        ...
                        const H_COUNT = 7;
                        ...
                        private
                          Fh: array[1..H_COUNT] of Double;
                          function GetArray(Index: Integer): Double;
                          procedure SetArray(Index: Integer; const Value: Double);
                        ...
                        published
                          property H[index: integer]: Double read GetArray write SetArray;
                         
                        ...
                        implementation
                        ...
                         
                        function MyComponent.GetArray(Index: Integer): Double;
                        begin
                          Result := Fh[Index];
                        end;
                         
                        procedure MyComponent.SetArray(Index: Integer; const Value: Double);
                        begin
                          Fh[Index] := Value;
                        end;

                      Как-то так. Стоит, наверное, еще добавить и проверку Index'а.
                      Сообщение отредактировано: Keeper89 -
                        Спасибо за помощь. все получилось.
                        0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)
                        0 пользователей:


                        Рейтинг@Mail.ru
                        [ Script execution time: 0,0370 ]   [ 16 queries used ]   [ Generated: 25.04.24, 15:53 GMT ]