IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

 Delphi Discussion :

Simplification de code : Multiple ajout d'objet à une liste d'objet


Sujet :

Delphi

  1. #1
    Membre habitué
    Profil pro
    Inscrit en
    Avril 2008
    Messages
    390
    Détails du profil
    Informations personnelles :
    Âge : 34
    Localisation : France

    Informations forums :
    Inscription : Avril 2008
    Messages : 390
    Points : 127
    Points
    127
    Par défaut Simplification de code : Multiple ajout d'objet à une liste d'objet
    Bonjour , voici mon code :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
     
     
      ListObject := TListObject.Create();
     
      // FR
      aObject := TObject.Create();
      aObject.StoreCode := 'fr';
      aObject.Title := 'TitleFR';
     
      ListObject.Add(aObject);
     
      // DE
      aObject := TObject.Create();
      aObject.StoreCode := 'de';
      aObject.Title := 'TitleDE';
     
      ListObject.Add(aObject);
     
      // EN
      aObject := TObject.Create();
      aObject.StoreCode := 'en';
      aObject.Title := 'TitleEN';
     
      ListObject.Add(aObject);
     
      // IT
      aObject := TObject.Create();
      aObject.StoreCode := 'it';
      aObject.Title := 'TitleIT';
     
      ListObject.Add(aObject);
    Je cherche un moyen de simplifier/réduire ce bout de code. J'ai cherché du code inline mais je ne me rappelle plus de la syntaxe. Avez-vous une idée ? (à part surcharger le consctructor )
    Le temps est le pire enemi de l'homme

  2. #2
    Expert éminent sénior
    Avatar de ShaiLeTroll
    Homme Profil pro
    Développeur C++\Delphi
    Inscrit en
    Juillet 2006
    Messages
    13 451
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 43
    Localisation : France, Seine Saint Denis (Île de France)

    Informations professionnelles :
    Activité : Développeur C++\Delphi
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juillet 2006
    Messages : 13 451
    Points : 24 859
    Points
    24 859
    Par défaut
    TObject déjà comme nom de classe, ce n'est pas terrible !
    Il suffit de faire un constructeur mais tu ne veux pas

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    constructor TMyObject.Create(const AStoreCode: string; const ATitle: string);
    begin
      inherited Create();
     
      FStoreCode := AStoreCode;
      FTitle := ATitle;
    end;
    pourtant c'est si simple ensuite

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
     
      ListObject := TListObject.Create(True); // si c'est uneSystem.Contnrs.TObjectList ou une  System.Generics.Collection.TObjectList<TMyObject>, la liste gère la libération
      ListObject.Add(TMyObject.Create('fr', 'TitleFR'));
      ListObject.Add(TMyObject.Create('de', 'TitleDE'));
      ListObject.Add(TMyObject.Create('en', 'TitleEN'));
      ListObject.Add(TMyObject.Create('it', 'TitleIT'));
    Je ne vois pas l'intérêt du inline

    sauf si tu veux faire un truc du genre

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
     
     
    procedure AddObject(AList: TListObject; const AStoreCode: string; const ATitle: string); // dans la section interface : inline;
    var
      aObject: TMyObject;
    begin
      aObject := TObject.Create();
      aObject.StoreCode := AStoreCode;
      aObject.Title := ATitle;
     
      AList.Add(aObject);
    end;
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
     
    procedure ...
    var
      ListObject: TListObject; 
    begin
      ListObject := TListObject.Create();
      AddObject(ListObject, 'fr', 'TitleFR'));
      AddObject(ListObject, 'de', 'TitleDE'));
      AddObject(ListObject, 'en', 'TitleEN');
      AddObject(ListObject, 'it', 'TitleIT');
    Mais bon ma proposition est si simple que cela ne doit pas être ce que tu veux, tu n'aurais pas eu besoin de poser la question pour ce genre de refactoring





    Si tu fais un système de traduction, je m'en suis fait assez simpliste basé sur des tableaux

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
     
     
      EXXXXLanguageException = class(Exception);
     
      /// <summary>TXXXXLanguage est une gestion très limitée de langues avec la traduction intégrée au code source</summary>
      /// <remarks>TXXXXLanguage est a utilisé UNIQUEMENT pour les codes communs qui évolue rarement</remarks>
      /// <remarks>C'est aussi très utile pour gérer une langue séparée entre celle de l'utilisateur et celle d'un destinataire d'un document</remarks>
      TXXXXLanguage = record
      public
        type
          TManagedLanguage = (mlEnglish, mlSpanish, mlFrench, mlDeutsch, mlItalian, mlZhuang, mlChinese);
          TManagedLanguageArray = array[TManagedLanguage] of string;
          /// <remarks>TManagedLanguageArrayEx est plus facile à maintenir</remarks>
          TManagedLanguageArrayEx = record
            English: string;
            Spanish: string;
            French: string;
            Deutsch: string;
            Italian: string;
            Zhuang: string;
            Chinese: string;
          public
            function Get(ALanguage: TManagedLanguage): string;
            function ToArray(): TManagedLanguageArray;
          end;
     
          TTranslatorFunc = function(const AMsg: string): string;
        const
          // Do not localize
          XXXX_MANAGED_LANGUAGE_CODES: TManagedLanguageArray = ('en', 'es', 'fr', 'de', 'it', 'za', 'zh');
          XXXX_MANAGED_LANGUAGE_LABELS: TManagedLanguageArray = ('Anglais', 'Espagnol', 'Français', 'Allemand', 'Italien', 'Chinois Simplifié (Zhuang)', 'Chinois Traditionnel');
          XXXX_MANAGED_LANGUAGE_LABEL_TRADUCTIONS: array[0..6] of TXXXXLanguage.TManagedLanguageArrayEx =
            (
              (English: 'English';                      Spanish: 'Inglés';                          French: 'Anglais';                     Deutsch: 'English';                       Italian: 'English';                       ),
              (English: 'Spanish';                      Spanish: 'Español';                         French: 'Espagnol';                    Deutsch: 'Spanish';                       Italian: 'Espagnol';                      ),
              (English: 'French';                       Spanish: 'Francés';                         French: 'Français';                    Deutsch: 'French';                        Italian: 'Francese';                      ),
              (English: 'Deutsch';                      Spanish: 'Deutsch';                         French: 'Allemand';                    Deutsch: 'Deutsch';                       Italian: 'Deutsch';                       ),
              (English: 'Italian';                      Spanish: 'Italiano';                        French: 'Italien';                     Deutsch: 'Italian';                       Italian: 'Italiana';                      ),
              (English: 'Simplified Chinese (Zhuang)';  Spanish: 'Chino Simplificado (Zhuang)';     French: 'Chinois Simplifié (Zhuang)';  Deutsch: 'Simplified Chinese (Zhuang)';   Italian: 'Cinese (Zhuang)';               ),
              (English: 'Traditional Chinese';          Spanish: 'Tradicional China';               French: 'Chinois Traditionnel';        Deutsch: 'Traditional Chinese';           Italian: 'Cinese Tradizionale';           )
            );
          MENU_DEFAULT_LANG = 'Défaut';
          MENU_DEFAULT_LANG_TRADUCTIONS: array[0..0] of TXXXXLanguage.TManagedLanguageArrayEx =
            (
              (English: 'Default module language';      Spanish: 'Idioma predeterminado del módula';French: 'Langue par défaut du module'; Deutsch: 'Default module language';       Italian: 'Lingua predefinita del modulo' )
            );
      private
        type
          TLanguageDomains = class;
          TLanguageMatrix = class;
          TLanguageMatrixItem = class;
     
          TLanguageDomains = class(TStringList)
          private
            function GetMatrix(const ADomain: string): TLanguageMatrix;
         public
            constructor Create();
     
            procedure AddMatrixItem(const ADomain: string; AReferenceLanguage: TManagedLanguage; AItem: TLanguageMatrixItem); overload;
            procedure AddMatrixItem(const ADomain: string; const AKey: string; AItem: TLanguageMatrixItem); overload;
     
            property Matrixes[const ADomain: string]: TLanguageMatrix read GetMatrix;
          end;
          TLanguageMatrix = class(TStringList)
          private
            function GetItem(Index: Integer): TLanguageMatrixItem;
          public
            constructor Create;
     
            procedure AddMatrixItem(const AKey: string; AItem: TLanguageMatrixItem);
     
            function Translate(ALanguage: TManagedLanguage; const AMsg: string): string; overload;
            function Translate(ALanguage: TManagedLanguage; const AControlName: string; const AMsg: string): string; overload;
            procedure Translate(ALanguage: TManagedLanguage; AControlOwner: TComponent; const AControlNames: array of string); overload;
     
            property Items[Index: Integer]: TLanguageMatrixItem read GetItem;
          end;
          TLanguageMatrixItem = class(TObject)
          private
            FTexts: TManagedLanguageArray;
            function GetText(ALanguage: TManagedLanguage): string;
          public
            constructor Create(const ATexts: TManagedLanguageArray);
            property Texts[ALanguage: TManagedLanguage]: string read GetText;
          end;
      strict private
        class var FDefaultLanguage: TManagedLanguage;
        class var FCurrentLanguage: TManagedLanguage;
        class var FLanguageDomains: TLanguageDomains;
     
        class function GetCurrentLanguageCode(): string; static;
        class function GetDefaultLanguageCode(): string; static;
        class procedure SetCurrentLanguageCode(const Value: string); static;
        class procedure SetDefaultLanguageCode(const Value: string); static;
      public
        class constructor Create();
        class destructor Destroy();
     
        class procedure BuildLangMenu(ACurrentLanguage: string; ALanguages: TStrings; AMenu: TMenuItem; AOnMenuClick: TNotifyEvent; ATranslator: TTranslatorFunc = nil); static;
        class procedure AddMatrix(const ADomain: string; AReferenceLanguage: TManagedLanguage; const AMatrix: array of TManagedLanguageArray); overload; static;
        class procedure AddMatrix(const ADomain: string; AReferenceLanguage: TManagedLanguage; const AMatrix: array of TManagedLanguageArrayEx); overload; static;
        class procedure AddMatrix(const ADomain: string; const AControlNames: array of string; const AMatrix: array of TManagedLanguageArrayEx); overload; static;
        class function Translate(const ADomain: string; const AMsg: string): string; overload; static;
        class function Translate(ALanguage: TManagedLanguage; const ADomain: string; const AMsg: string): string; overload; static;
        class procedure Translate(ALanguage: TManagedLanguage; const ADomain: string; AControlOwner: TComponent; const AControlNames: array of string); overload; static;
        class function DefaultLanguageLabelsTranslator(const ALanguageLabel: string): string; static;
     
        class function CodeToIdent(const ACode: string): TManagedLanguage; static;
        class function TryCodeToIdent(const ACode: string; out AIdent: TManagedLanguage): Boolean; static;
        class function IdentToCode(const AIdent: TManagedLanguage): string; static;
        class function ChangeLangByMenu(AMenu: TObject): TManagedLanguage; overload; static;
        class function ChangeLangByMenu(AMenu: TObject; const ADomain: string; AControlOwner: TComponent; const AControlNames: array of string): TManagedLanguage; overload; static;
     
        class property CurrentLanguage: TManagedLanguage read FCurrentLanguage write FCurrentLanguage;
        class property CurrentLanguageCode: string read GetCurrentLanguageCode write SetCurrentLanguageCode;
        class property DefaultLanguage: TManagedLanguage read FDefaultLanguage write FDefaultLanguage;
        class property DefaultLanguageCode: string read GetDefaultLanguageCode write SetDefaultLanguageCode;
      end;
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
     
    { TXXXXLanguage - Procédural }
     
    //------------------------------------------------------------------------------
    function _Format(ADomain: TClass; const AMsg: string; const Args: array of const): string;
    begin
      Result := Format(TXXXXLanguage.Translate(ADomain.ClassName(), AMsg), Args);
    end;
     
    { TXXXXLanguage }
     
    //------------------------------------------------------------------------------
    class procedure TXXXXLanguage.AddMatrix(const ADomain: string; AReferenceLanguage: TManagedLanguage; const AMatrix: array of TManagedLanguageArray);
    var
      I: Integer;
    begin
      for I := Low(AMatrix) to High(AMatrix) do
        FLanguageDomains.AddMatrixItem(ADomain, AReferenceLanguage, TLanguageMatrixItem.Create(AMatrix[I]));
    end;
     
    //------------------------------------------------------------------------------
    class procedure TXXXXLanguage.AddMatrix(const ADomain: string; AReferenceLanguage: TManagedLanguage; const AMatrix: array of TManagedLanguageArrayEx);
    var
      I: Integer;
    begin
      for I := Low(AMatrix) to High(AMatrix) do
        FLanguageDomains.AddMatrixItem(ADomain, AReferenceLanguage, TLanguageMatrixItem.Create(AMatrix[I].ToArray()));
    end;
     
    //------------------------------------------------------------------------------
    class procedure TXXXXLanguage.AddMatrix(const ADomain: string; const AControlNames: array of string; const AMatrix: array of TManagedLanguageArrayEx);
    var
      I: Integer;
    begin
      if Length(AControlNames) <> Length(AMatrix) then
        raise EXXXXLanguageException.CreateFmt('Domain "%s" - Length(AControlNames) <> Length(AMatrix)', [ADomain]); // Do not localize
     
      for I := Low(AMatrix) to High(AMatrix) do
        FLanguageDomains.AddMatrixItem(ADomain, AControlNames[I], TLanguageMatrixItem.Create(AMatrix[I].ToArray()));
    end;
     
    //------------------------------------------------------------------------------
    class procedure TXXXXLanguage.BuildLangMenu(ACurrentLanguage: string; ALanguages: TStrings; AMenu: TMenuItem; AOnMenuClick: TNotifyEvent; ATranslator: TTranslatorFunc = nil);
    var
      I, itml: Integer;
      mi: TMenuItem;
      CurrentLanguageChecked: Boolean;
    begin
      AMenu.Clear();
     
      CurrentLanguageChecked := False;
      for I := 0 to ALanguages.Count - 1 do
      begin
        mi := TMenuItem.Create(AMenu);
     
        itml := IndexStr(ALanguages[I], XXXX_MANAGED_LANGUAGE_CODES);
        if Assigned(ATranslator) and (itml in [Ord(Low(TManagedLanguage))..Ord(High(TManagedLanguage))]) then
          mi.Caption := ALanguages[I] + ' - ' + ATranslator(XXXX_MANAGED_LANGUAGE_LABELS[TManagedLanguage(itml)])
        else
          mi.Caption := ALanguages[I];
     
        mi.Hint := ALanguages[I];
        mi.OnClick := AOnMenuClick;
        if ACurrentLanguage = ALanguages[I] then
        begin
          mi.Checked := True;
          CurrentLanguageChecked := True;
        end;
        mi.AutoCheck := True;
        mi.RadioItem := True;
        mi.GroupIndex := 1;
        AMenu.Add(mi);
      end;
     
      mi := TMenuItem.Create(AMenu);
      if Assigned(ATranslator) then
        mi.Caption := ATranslator(MENU_DEFAULT_LANG)
      else
        mi.Caption := MENU_DEFAULT_LANG;
      mi.Hint := EmptyStr;
      mi.OnClick := AOnMenuClick;
      mi.Checked := not CurrentLanguageChecked;
      mi.AutoCheck := False; // AutoCheck décoche automatiquement ce qu'il ne faut pas !
      mi.RadioItem := True;
      mi.GroupIndex := 1;
      AMenu.Add(mi);
    end;
     
    //------------------------------------------------------------------------------
    class function TXXXXLanguage.ChangeLangByMenu(AMenu: TObject): TManagedLanguage;
    begin
      if Assigned(AMenu) then
      begin
        if AMenu is TMenuItem then
        begin
          if TMenuItem(AMenu).Hint <> '' then
            Result := CodeToIdent(TMenuItem(AMenu).Hint)
          else
            Result := TXXXXLanguage.DefaultLanguage;
     
          CurrentLanguage := Result;
          TMenuItem(AMenu).Checked := True;
        end
        else
          raise EConvertError.CreateFmt('This Sender of class "%s" is not a Language Element supported by XXXX Language API', [AMenu.ClassName()]);
      end
      else
        raise EConvertError.Create('A "nil" Sender not supported by XXXX Language API');
    end;
     
    //------------------------------------------------------------------------------
    class function TXXXXLanguage.ChangeLangByMenu(AMenu: TObject; const ADomain: string; AControlOwner: TComponent; const AControlNames: array of string): TManagedLanguage;
    begin
      Result := ChangeLangByMenu(AMenu);
      Translate(Result, ADomain, AControlOwner, AControlNames);
    end;
     
    //------------------------------------------------------------------------------
    class function TXXXXLanguage.CodeToIdent(const ACode: string): TManagedLanguage;
    begin
      if not TryCodeToIdent(ACode, Result) then
        raise EConvertError.CreateFmt('Code "%s" is not a Language supported by XXXX Language API', [ACode]);
    end;
     
    //------------------------------------------------------------------------------
    class constructor TXXXXLanguage.Create();
    begin
      FDefaultLanguage := mlFrench;
      FCurrentLanguage := mlFrench;
      FLanguageDomains := TLanguageDomains.Create();
     
      TXXXXLanguage.AddMatrix('XXXXLanguage\Languages', TXXXXLanguage.TManagedLanguage.mlFrench, TXXXXLanguage.XXXX_MANAGED_LANGUAGE_LABEL_TRADUCTIONS);
      TXXXXLanguage.AddMatrix('XXXXLanguage\Default', TXXXXLanguage.TManagedLanguage.mlFrench, TXXXXLanguage.MENU_DEFAULT_LANG_TRADUCTIONS);
    end;
     
    //------------------------------------------------------------------------------
    class function TXXXXLanguage.DefaultLanguageLabelsTranslator(const ALanguageLabel: string): string;
    begin
      if ALanguageLabel = MENU_DEFAULT_LANG then
        Result := Translate(FCurrentLanguage, 'XXXXLanguage\Default', MENU_DEFAULT_LANG_TRADUCTIONS[0].French)
      else
        Result := Translate(FCurrentLanguage, 'XXXXLanguage\Languages', ALanguageLabel);
    end;
     
    //------------------------------------------------------------------------------
    class destructor TXXXXLanguage.Destroy();
    begin
      FreeAndNil(FLanguageDomains);
    end;
     
    //------------------------------------------------------------------------------
    class function TXXXXLanguage.GetCurrentLanguageCode(): string;
    begin
      Result := XXXX_MANAGED_LANGUAGE_CODES[CurrentLanguage];
    end;
     
    //------------------------------------------------------------------------------
    class function TXXXXLanguage.GetDefaultLanguageCode(): string;
    begin
      Result := XXXX_MANAGED_LANGUAGE_CODES[DefaultLanguage];
    end;
     
    //------------------------------------------------------------------------------
    class function TXXXXLanguage.IdentToCode(const AIdent: TManagedLanguage): string;
    begin
      Result := XXXX_MANAGED_LANGUAGE_CODES[AIdent];
    end;
     
    //------------------------------------------------------------------------------
    class function TXXXXLanguage.Translate(const ADomain: string; const AMsg: string): string;
    begin
      Result := Translate(FCurrentLanguage, ADomain, AMsg);
    end;
     
    //------------------------------------------------------------------------------
    class function TXXXXLanguage.Translate(ALanguage: TManagedLanguage; const ADomain: string; const AMsg: string): string;
    begin
      Result := FLanguageDomains.Matrixes[ADomain].Translate(ALanguage, AMsg);
    end;
     
    //------------------------------------------------------------------------------
    class procedure TXXXXLanguage.Translate(ALanguage: TManagedLanguage; const ADomain: string; AControlOwner: TComponent; const AControlNames: array of string);
    begin
      FLanguageDomains.Matrixes[ADomain].Translate(ALanguage, AControlOwner, AControlNames);
    end;
     
    //------------------------------------------------------------------------------
    class function TXXXXLanguage.TryCodeToIdent(const ACode: string; out AIdent: TManagedLanguage): Boolean;
    var
      I: Integer;
    begin
      I := IndexText(ACode, XXXX_MANAGED_LANGUAGE_CODES);
      Result := (Ord(Low(FCurrentLanguage)) <= I) and (I <= Ord(High(FCurrentLanguage)));
      if Result then
        AIdent := TManagedLanguage(I);
    end;
     
    //------------------------------------------------------------------------------
    class procedure TXXXXLanguage.SetCurrentLanguageCode(const Value: string);
    begin
      if Value <> '' then
        TryCodeToIdent(Value, FCurrentLanguage)
      else
        FCurrentLanguage := DefaultLanguage;
    end;
     
    //------------------------------------------------------------------------------
    class procedure TXXXXLanguage.SetDefaultLanguageCode(const Value: string);
    begin
      TryCodeToIdent(Value, FDefaultLanguage);
    end;
     
     
    { TXXXXLanguage.TLanguageDomains }
     
    //------------------------------------------------------------------------------
    procedure TXXXXLanguage.TLanguageDomains.AddMatrixItem(const ADomain: string; AReferenceLanguage: TManagedLanguage; AItem: TLanguageMatrixItem);
    begin
      AddMatrixItem(ADomain, AItem.Texts[AReferenceLanguage], AItem);
    end;
     
    //------------------------------------------------------------------------------
    procedure TXXXXLanguage.TLanguageDomains.AddMatrixItem(const ADomain: string; const AKey: string; AItem: TLanguageMatrixItem);
    var
      I: Integer;
      Matrix: TLanguageMatrix;
    begin
      I := IndexOf(ADomain);
      if I < 0 then
      begin
        Matrix := TLanguageMatrix.Create();
        AddObject(ADomain, Matrix);
      end
      else
        Matrix := Objects[I] as TLanguageMatrix;
     
      Matrix.AddMatrixItem(AKey, AItem);
    end;
     
    //------------------------------------------------------------------------------
    constructor TXXXXLanguage.TLanguageDomains.Create();
    begin
      inherited Create(True);
      Duplicates := dupError;
      Sorted := True;
    end;
     
    //------------------------------------------------------------------------------
    function TXXXXLanguage.TLanguageDomains.GetMatrix(const ADomain: string): TLanguageMatrix;
    var
      I: Integer;
    begin
      I := IndexOf(ADomain);
      if I >= 0 then
        Result := Objects[I] as TLanguageMatrix
      else
        raise EXXXXLanguageException.CreateFmt('Invalid Domain : "%s"', [ADomain]); // Do not localize
    end;
     
    { TXXXXLanguage.TLanguageMatrix }
     
    //------------------------------------------------------------------------------
    procedure TXXXXLanguage.TLanguageMatrix.AddMatrixItem(const AKey: string; AItem: TLanguageMatrixItem);
    begin
      AddObject(AKey, AItem);
    end;
     
    //------------------------------------------------------------------------------
    constructor TXXXXLanguage.TLanguageMatrix.Create();
    begin
      inherited Create(True);
      Duplicates := dupError;
      Sorted := True;
    end;
     
    //------------------------------------------------------------------------------
    function TXXXXLanguage.TLanguageMatrix.GetItem(Index: Integer): TLanguageMatrixItem;
    begin
      Result := TLanguageMatrixItem(Objects[Index]);
    end;
     
    //------------------------------------------------------------------------------
    function TXXXXLanguage.TLanguageMatrix.Translate(ALanguage: TManagedLanguage; const AControlName: string; const AMsg: string): string;
    var
      I: Integer;
    begin
      I := IndexOf(AControlName);
      if I >= 0 then
      begin
        Result := Items[I].Texts[ALanguage];
        if Result = '' then
          Result := AMsg;
      end
      else
        Result := AMsg;
    end;
     
    //------------------------------------------------------------------------------
    procedure TXXXXLanguage.TLanguageMatrix.Translate(ALanguage: TManagedLanguage; AControlOwner: TComponent; const AControlNames: array of string);
    var
      I: Integer;
      C: TComponent;
      LPropInfo: System.TypInfo.PPropInfo;
    begin
      for I := Low(AControlNames) to High(AControlNames) do
      begin
        C := AControlOwner.FindComponent(AControlNames[I]);
        if Assigned(C) then
        begin
          LPropInfo := TXXXXRTTI.GetPropertyInfo(C.ClassType(), 'Caption');
          if Assigned(LPropInfo) and (LPropInfo^.PropType^.Kind = System.TypInfo.tkUString) then
            System.TypInfo.SetStrProp(C, 'Caption', Translate(ALanguage, AControlNames[I], System.TypInfo.GetStrProp(C, 'Caption')));
        end;
      end;
    end;
     
    //------------------------------------------------------------------------------
    function TXXXXLanguage.TLanguageMatrix.Translate(ALanguage: TManagedLanguage; const AMsg: string): string;
    var
      I: Integer;
    begin
      I := IndexOf(AMsg);
      if I >= 0 then
      begin
        Result := Items[I].Texts[ALanguage];
        if Result = '' then
          Result := AMsg;
      end
      else
        Result := AMsg;
    end;
     
    { TXXXXLanguage.TLanguageMatrixItem }
     
    //------------------------------------------------------------------------------
    constructor TXXXXLanguage.TLanguageMatrixItem.Create(const ATexts: TManagedLanguageArray);
    begin
      inherited Create();
     
      FTexts := ATexts;
    end;
     
    //------------------------------------------------------------------------------
    function TXXXXLanguage.TLanguageMatrixItem.GetText(ALanguage: TManagedLanguage): string;
    begin
      Result := FTexts[ALanguage];
    end;
     
    { TXXXXLanguage.TManagedLanguageArrayEx }
     
    //------------------------------------------------------------------------------
    function TXXXXLanguage.TManagedLanguageArrayEx.Get(ALanguage: TManagedLanguage): string;
    begin
      case ALanguage of
        mlEnglish : Result := English;
        mlSpanish : Result := Spanish;
        mlFrench  : Result := French;
        mlDeutsch : Result := Deutsch;
        mlItalian : Result := Italian;
        mlZhuang  : Result := Zhuang;
        mlChinese : Result := Chinese;
      else
        Result := '';
      end;
    end;
     
    //------------------------------------------------------------------------------
    function TXXXXLanguage.TManagedLanguageArrayEx.ToArray(): TManagedLanguageArray;
    begin
      Result[mlEnglish] := English;
      Result[mlSpanish] := Spanish;
      Result[mlFrench] := French;
      Result[mlDeutsch] := Deutsch;
      Result[mlItalian] := Italian;
      Result[mlZhuang] := Zhuang;
      Result[mlChinese] := Chinese;
    end;
    Aide via F1 - FAQ - Guide du développeur Delphi devant un problème - Pensez-y !
    Attention Troll Méchant !
    "Quand un homme a faim, mieux vaut lui apprendre à pêcher que de lui donner un poisson" Confucius
    Mieux vaut se taire et paraître idiot, Que l'ouvrir et de le confirmer !
    L'ignorance n'excuse pas la médiocrité !

    L'expérience, c'est le nom que chacun donne à ses erreurs. (Oscar Wilde)
    Il faut avoir le courage de se tromper et d'apprendre de ses erreurs

  3. #3
    Membre habitué
    Profil pro
    Inscrit en
    Avril 2008
    Messages
    390
    Détails du profil
    Informations personnelles :
    Âge : 34
    Localisation : France

    Informations forums :
    Inscription : Avril 2008
    Messages : 390
    Points : 127
    Points
    127
    Par défaut
    Le code affiché n'est pas vraiment "l'officiel", évidement TObject n'est pas le nom de mon objet.

    Pour ta réponse, c'est la solution que j'ai actuellement, mais je voulais savoir s'il y avait une autre solution

    Je ne fais pas un système de traduction mais je garde ce code de côté

    merci
    Le temps est le pire enemi de l'homme

  4. #4
    Expert éminent sénior
    Avatar de ShaiLeTroll
    Homme Profil pro
    Développeur C++\Delphi
    Inscrit en
    Juillet 2006
    Messages
    13 451
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 43
    Localisation : France, Seine Saint Denis (Île de France)

    Informations professionnelles :
    Activité : Développeur C++\Delphi
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juillet 2006
    Messages : 13 451
    Points : 24 859
    Points
    24 859
    Par défaut
    Citation Envoyé par lerorodu51 Voir le message
    Pour ta réponse, c'est la solution que j'ai actuellement, mais je voulais savoir s'il y avait une autre solution
    Laquelle ?
    Celle du constructor ?
    Celle du AddObject ?
    Aide via F1 - FAQ - Guide du développeur Delphi devant un problème - Pensez-y !
    Attention Troll Méchant !
    "Quand un homme a faim, mieux vaut lui apprendre à pêcher que de lui donner un poisson" Confucius
    Mieux vaut se taire et paraître idiot, Que l'ouvrir et de le confirmer !
    L'ignorance n'excuse pas la médiocrité !

    L'expérience, c'est le nom que chacun donne à ses erreurs. (Oscar Wilde)
    Il faut avoir le courage de se tromper et d'apprendre de ses erreurs

  5. #5
    Expert éminent sénior
    Avatar de ShaiLeTroll
    Homme Profil pro
    Développeur C++\Delphi
    Inscrit en
    Juillet 2006
    Messages
    13 451
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 43
    Localisation : France, Seine Saint Denis (Île de France)

    Informations professionnelles :
    Activité : Développeur C++\Delphi
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juillet 2006
    Messages : 13 451
    Points : 24 859
    Points
    24 859
    Par défaut
    Citation Envoyé par SergioMaster Voir le message
    il suffit de créer une méthode create pour un objet spécifique les 2 propriétés
    Justement, il ne veut pas
    EDIT : finalement, tu as supprimé ta réponse

    Citation Envoyé par lerorodu51 Voir le message
    Avez-vous une idée ? (à part surcharger le consctructor )
    Du coup, je lui ai proposé un AddObject

    Et j'en vois une troisième TStoreList.AddStore que je pratique assez souvent (qui n'est en général qu'un raccourci pour un Create spécifique + Add)


    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    procedure TStoreList.AddStore(const AStoreCode: string; const ATitle: string); 
      aObject: TStore;
    begin
      aObject := TStore.Create();
      aObject.StoreCode := AStoreCode;
      aObject.Title := ATitle;
     
      Self.Add(aObject);
    end;
    ou

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    procedure TStoreList.AddStore(const AStoreCode: string; const ATitle: string); 
    begin
      Self.Add(TStore.Create(AStoreCode, ATitle));
    end;

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    procedure ...
    var
      ListS: TStoreList; 
    begin
      ListS:= TStoreList.Create();
      ListS.AddStore('fr', 'TitleFR'));
      ListS.AddStore('de', 'TitleDE'));
      ListS.AddStore('en', 'TitleEN');
      ListS.AddStore('it', 'TitleIT');
    Aide via F1 - FAQ - Guide du développeur Delphi devant un problème - Pensez-y !
    Attention Troll Méchant !
    "Quand un homme a faim, mieux vaut lui apprendre à pêcher que de lui donner un poisson" Confucius
    Mieux vaut se taire et paraître idiot, Que l'ouvrir et de le confirmer !
    L'ignorance n'excuse pas la médiocrité !

    L'expérience, c'est le nom que chacun donne à ses erreurs. (Oscar Wilde)
    Il faut avoir le courage de se tromper et d'apprendre de ses erreurs

  6. #6
    Membre habitué
    Profil pro
    Inscrit en
    Avril 2008
    Messages
    390
    Détails du profil
    Informations personnelles :
    Âge : 34
    Localisation : France

    Informations forums :
    Inscription : Avril 2008
    Messages : 390
    Points : 127
    Points
    127
    Par défaut
    Celle du constructor.

    Pour la solution du addObject, j'y avais pensé aussi mais je cherchais du code qui simplifie au max mon bout de code (j'avais une idée en tête mais je crois que c'était en c#...)

    Je vais rester sur l'overload du constructor .

    Merci à vous.
    Le temps est le pire enemi de l'homme

  7. #7
    Expert éminent sénior
    Avatar de ShaiLeTroll
    Homme Profil pro
    Développeur C++\Delphi
    Inscrit en
    Juillet 2006
    Messages
    13 451
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 43
    Localisation : France, Seine Saint Denis (Île de France)

    Informations professionnelles :
    Activité : Développeur C++\Delphi
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juillet 2006
    Messages : 13 451
    Points : 24 859
    Points
    24 859
    Par défaut
    Par curiosité, en C#, tu fais comment, genre une méthode générique ou une expression lambda ?
    Je ne connais pas ces nouvelles syntaxes ultra compacts, déjà, je trouve que c'est pas mal
    Aide via F1 - FAQ - Guide du développeur Delphi devant un problème - Pensez-y !
    Attention Troll Méchant !
    "Quand un homme a faim, mieux vaut lui apprendre à pêcher que de lui donner un poisson" Confucius
    Mieux vaut se taire et paraître idiot, Que l'ouvrir et de le confirmer !
    L'ignorance n'excuse pas la médiocrité !

    L'expérience, c'est le nom que chacun donne à ses erreurs. (Oscar Wilde)
    Il faut avoir le courage de se tromper et d'apprendre de ses erreurs

  8. #8
    Membre habitué
    Profil pro
    Inscrit en
    Avril 2008
    Messages
    390
    Détails du profil
    Informations personnelles :
    Âge : 34
    Localisation : France

    Informations forums :
    Inscription : Avril 2008
    Messages : 390
    Points : 127
    Points
    127
    Par défaut
    j'utilise ce genre de code :

    Code c++ : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
     
    IList<Student> studentList = new List<Student>() { 
                    new Student(){ StudentID=1, StudentName="Bill"},
                    new Student(){ StudentID=2, StudentName="Steve"},
                    new Student(){ StudentID=3, StudentName="Ram"},
                    new Student(){ StudentID=1, StudentName="Moin"}
                };

    ce qui est semblabe à notre surcharge de constructeur mais dans ce cas là , je ne fait pas de surcharge
    Le temps est le pire enemi de l'homme

  9. #9
    Expert éminent sénior
    Avatar de Paul TOTH
    Homme Profil pro
    Freelance
    Inscrit en
    Novembre 2002
    Messages
    8 964
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 54
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Freelance
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Novembre 2002
    Messages : 8 964
    Points : 28 430
    Points
    28 430
    Par défaut
    en effet Delphi ne permet pas ce genre de déclaration, le plus approchant (mais pourquoi voudrait-on s'approcher de C# en Pascal ?) serait

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
     
    begin
      stundentList := TStudentList.Create([
        TStudent.Create(1, 'Bill'),
        TStudent.Create(2, 'Steve'),
        TStudent.Create(3, 'Ram'),
        TStudent.Create(1, 'Moi')
      ]);
    end;
    ce qui impose cependant d'avoir un constructor spécifique pour TStudent un TStudentList

    mais quand il est question d'utiliser des constantes, j'utilise des constantes

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
     
     
    type
      TStudentRecord = record
        Id  : Integer;
        Name: string;
      end;
     
      TStudent = class
      private
        FData: TStudentRecord;
      public
        constructor Create(const AData: TStudentRecord); overload;
        constructor Create(Id: Integer; Name: string); overload;
        property StudentId: Integer read FData.Id;
        property StudentName: string read FData.Name;
      end;
     
      TStudentList = class(TList)
      private
        function GetItem(Index: Integer): TStudent;
      public
        constructor Create(const Students: array of TStudentRecord) overload;
        constructor Create(const Students: array of TStudent) overload;
        procedure Clear; override;
        property Items[Index: Integer]: TStudent read GetItem; default;
      end;
     
    constructor TStudent.Create(const AData: TStudentRecord);
    begin
      FData := AData;
    end;
     
    constructor TStudent.Create(Id: Integer; Name: string);
    begin
      FData.Id := Id;
      FData.Name := Name;
    end;
     
    constructor TStudentList.Create(const Students: array of TStudentRecord);
    var
      Index: Integer;
    begin
      inherited Create;
      for Index := Low(Students) to High(Students) do
      begin
        Add(TStudent.Create(Students[Index]));
      end;
    end;
     
    constructor TStudentList.Create(const Students: array of TStudent);
    var
      Index: Integer;
    begin
      inherited Create;
      for Index := Low(Students) to High(Students) do
      begin
        Add(Students[Index]);
      end;
    end;
     
    procedure TStudentList.Clear;
    var
      Index: Integer;
    begin
      for Index := 0 to Count - 1 do
        Items[Index].Free;
      inherited;
    end;
     
    function TStudentList.GetItem(Index: Integer): TStudent;
    begin
      Result := List[Index];
    end;
     
    procedure TForm1.FormCreate(Sender: TObject);
    const
      Data: array[0..3] of TStudentRecord = (
       (Id: 1; Name: 'Bill'),
       (Id: 2; Name: 'Steve'),
       (Id: 3; Name: 'Ram'),
       (Id: 1; Name: 'Moin')
      );
    var
      StudentList : TStudentList;
    begin
    // Méthode 1
      StudentList := TStudentList.Create([
        TStudent.Create(1, 'Bill'),
        TStudent.Create(2, 'Steve'),
        TStudent.Create(3, 'Ram'),
        TStudent.Create(1, 'Moin')
      ]);
      ShowMessage(StudentList[1].StudentName);
      StudentList.Free;
     
    // Méthode 2
      StudentList := TStudentList.Create(Data);
      ShowMessage(StudentList[1].StudentName);
      StudentList.Free;
    end;
    Developpez.com: Mes articles, forum FlashPascal
    Entreprise: Execute SARL
    Le Store Excute Store

  10. #10
    Expert éminent sénior
    Avatar de ShaiLeTroll
    Homme Profil pro
    Développeur C++\Delphi
    Inscrit en
    Juillet 2006
    Messages
    13 451
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 43
    Localisation : France, Seine Saint Denis (Île de France)

    Informations professionnelles :
    Activité : Développeur C++\Delphi
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juillet 2006
    Messages : 13 451
    Points : 24 859
    Points
    24 859
    Par défaut
    Citation Envoyé par lerorodu51 Voir le message
    j'utilise ce genre de code :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
     
    IList<Student> studentList = new List<Student>() { 
                    new Student(){ StudentID=1, StudentName="Bill"},
                    new Student(){ StudentID=2, StudentName="Steve"},
                    new Student(){ StudentID=3, StudentName="Ram"},
                    new Student(){ StudentID=1, StudentName="Moin"}
                };
    ce qui est semblabe à notre surcharge de constructeur mais dans ce cas là , je ne fait pas de surcharge
    Ah c'est une forme d'initialisation de masse, OK
    J'aime bien la Méthode 2 de Paul TOTH, pour l'avoir utilisé très souvent avec plusieurs variantes de constantes

    Allez voici un truc bien horrible qui s'en approche
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    type
      TStudent = class
      private
        FStudentID: Integer;
        FStudentName: string;
      public
        property StudentID: Integer read FStudentID write FStudentID;
        property StudentName: string read FStudentName write FStudentName;
      end;
      TStudentList = System.Generics.Collections.TObjectList<TStudent>;
     
    procedure TZooXXXXVCLMainForm.Button2Click(Sender: TObject);
    var
      SL: TStudentList;
    begin
      SL := TStudentList.Create(True);
      with SL[SL.Add(TStudent.Create())] do begin StudentID := 1; StudentName := 'Bill'; end;
      with SL[SL.Add(TStudent.Create())] do begin StudentID := 2; StudentName := 'Steve'; end;
      with SL[SL.Add(TStudent.Create())] do begin StudentID := 3; StudentName := 'Ram'; end;
      with SL[SL.Add(TStudent.Create())] do begin StudentID := 4; StudentName := 'Moin'; end;
      ShowMessage(SL[1].StudentName);
      SL.Free;
    end;
    Aide via F1 - FAQ - Guide du développeur Delphi devant un problème - Pensez-y !
    Attention Troll Méchant !
    "Quand un homme a faim, mieux vaut lui apprendre à pêcher que de lui donner un poisson" Confucius
    Mieux vaut se taire et paraître idiot, Que l'ouvrir et de le confirmer !
    L'ignorance n'excuse pas la médiocrité !

    L'expérience, c'est le nom que chacun donne à ses erreurs. (Oscar Wilde)
    Il faut avoir le courage de se tromper et d'apprendre de ses erreurs

  11. #11
    Expert éminent sénior
    Avatar de ShaiLeTroll
    Homme Profil pro
    Développeur C++\Delphi
    Inscrit en
    Juillet 2006
    Messages
    13 451
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 43
    Localisation : France, Seine Saint Denis (Île de France)

    Informations professionnelles :
    Activité : Développeur C++\Delphi
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juillet 2006
    Messages : 13 451
    Points : 24 859
    Points
    24 859
    Par défaut
    Petite correction du code de Paul TOTH en s'appuyant sur le mécanisme de la TList
    Au lieu de redéfinir Clear (car faudrait aussi redéfinir le Delete), il vaut mieux redéfinir Notify (ou utiliser une TObjectList)

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    type
      TStudentRecord = record
        Id  : Integer;
        Name: string;
      end;
     
      TStudent = class
      private
        FData: TStudentRecord;
      public
        constructor Create(const AData: TStudentRecord); overload;
        constructor Create(Id: Integer; Name: string); overload;
        property StudentId: Integer read FData.Id;
        property StudentName: string read FData.Name;
      end;
     
      TStudentList = class(TList)
      private
        function GetItem(Index: Integer): TStudent;
      protected
        procedure Notify(Ptr: Pointer; Action: TListNotification); override;
      public
        constructor Create(const Students: array of TStudentRecord) overload;
        constructor Create(const Students: array of TStudent) overload;
        property Items[Index: Integer]: TStudent read GetItem; default;
      end;
     
    constructor TStudent.Create(const AData: TStudentRecord);
    begin
      FData := AData;
    end;
     
    constructor TStudent.Create(Id: Integer; Name: string);
    begin
      FData.Id := Id;
      FData.Name := Name;
    end;
     
    constructor TStudentList.Create(const Students: array of TStudentRecord);
    var
      Index: Integer;
    begin
      inherited Create;
      for Index := Low(Students) to High(Students) do
      begin
        Add(TStudent.Create(Students[Index]));
      end;
    end;
     
    constructor TStudentList.Create(const Students: array of TStudent);
    var
      Index: Integer;
    begin
      inherited Create;
      for Index := Low(Students) to High(Students) do
      begin
        Add(Students[Index]);
      end;
    end;
     
    function TStudentList.GetItem(Index: Integer): TStudent;
    begin
      Result := List[Index];
    end;
     
    procedure TStudentList.Notify(Ptr: Pointer; Action: TListNotification);
    begin
      if (Action = lnDeleted) then
        TObject(Ptr).Free;
      inherited Notify(Ptr, Action);
    end;
     
     
    procedure TZooXXXXVCLMainForm.Button2Click(Sender: TObject);
    const
      Data: array[0..3] of TStudentRecord = (
       (Id: 1; Name: 'Bill'),
       (Id: 2; Name: 'Steve'),
       (Id: 3; Name: 'Ram'),
       (Id: 1; Name: 'Moin')
      );
    var
      StudentList : TStudentList;
    begin
    // Méthode 1
      StudentList := TStudentList.Create([
        TStudent.Create(1, 'Bill'),
        TStudent.Create(2, 'Steve'),
        TStudent.Create(3, 'Ram'),
        TStudent.Create(1, 'Moin')
      ]);
      ShowMessage(StudentList[1].StudentName);
      StudentList.Free;
     
    // Méthode 2
      StudentList := TStudentList.Create(Data);
      ShowMessage(StudentList[1].StudentName);
      StudentList.Free;
    end;
    Aide via F1 - FAQ - Guide du développeur Delphi devant un problème - Pensez-y !
    Attention Troll Méchant !
    "Quand un homme a faim, mieux vaut lui apprendre à pêcher que de lui donner un poisson" Confucius
    Mieux vaut se taire et paraître idiot, Que l'ouvrir et de le confirmer !
    L'ignorance n'excuse pas la médiocrité !

    L'expérience, c'est le nom que chacun donne à ses erreurs. (Oscar Wilde)
    Il faut avoir le courage de se tromper et d'apprendre de ses erreurs

  12. #12
    Expert éminent sénior
    Avatar de Paul TOTH
    Homme Profil pro
    Freelance
    Inscrit en
    Novembre 2002
    Messages
    8 964
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 54
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Freelance
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Novembre 2002
    Messages : 8 964
    Points : 28 430
    Points
    28 430
    Par défaut
    Citation Envoyé par ShaiLeTroll Voir le message
    Petite correction du code de Paul TOTH en s'appuyant sur le mécanisme de la TList
    Au lieu de redéfinir Clear (car faudrait aussi redéfinir le Delete), il vaut mieux redéfinir Notify (ou utiliser une TObjectList)
    tu as tout à fait raison, mais je prend souvent le raccourci du Clear quand je sais qu'aucun élément ne sera détruit unitairement...ou même je crée une méthode FreeObjects qui est plus explicite que le Clear, mais du coup il ne faut pas oublier d'appeler FreeObjects au lieu de Clear
    Developpez.com: Mes articles, forum FlashPascal
    Entreprise: Execute SARL
    Le Store Excute Store

  13. #13
    Membre expérimenté
    Avatar de retwas
    Homme Profil pro
    Développeur Java/Delphi
    Inscrit en
    Mars 2010
    Messages
    698
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 32
    Localisation : France, Côte d'Or (Bourgogne)

    Informations professionnelles :
    Activité : Développeur Java/Delphi
    Secteur : Finance

    Informations forums :
    Inscription : Mars 2010
    Messages : 698
    Points : 1 608
    Points
    1 608
    Billets dans le blog
    4
    Par défaut
    Même si la discussion est fermée, le framework Spring4D contient énormément de type de liste.

    Dans l'unité Spring.Collections.Lists j'utilise la TList<T> qui donne accès directement au constructeur
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    public
     constructor Create(const values: array of T); override;
    Ça revient à surcharger le constructeur, mais dans ce cas c'est pas toi qui le fait et en plus tu as pas mal de méthodes intéressantes

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Réponses: 3
    Dernier message: 18/06/2009, 15h59
  2. Une Liste d'objets comme attribut d'objet
    Par koomkoom dans le forum Langage
    Réponses: 1
    Dernier message: 31/08/2008, 19h20
  3. Ajout de Node a partir d'objet contenant une liste d'objet
    Par Al_Bundy dans le forum Windows Forms
    Réponses: 4
    Dernier message: 05/08/2008, 14h35
  4. Réponses: 5
    Dernier message: 22/04/2008, 10h41
  5. Associer une liste d'objet à une clé
    Par fedfil dans le forum Collection et Stream
    Réponses: 2
    Dernier message: 07/06/2007, 10h45

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo