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

Langage Delphi Discussion :

Pourquoi pas de Booléen dans TTypeKind ?


Sujet :

Langage Delphi

  1. #1
    Expert éminent
    Avatar de Lung
    Profil pro
    Analyste-programmeur
    Inscrit en
    Mai 2002
    Messages
    2 678
    Détails du profil
    Informations personnelles :
    Âge : 44
    Localisation : France, Haute Savoie (Rhône Alpes)

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

    Informations forums :
    Inscription : Mai 2002
    Messages : 2 678
    Points : 7 093
    Points
    7 093
    Par défaut Pourquoi pas de Booléen dans TTypeKind ?
    Pour une application, j'ai eu besoin d'une variable pour stocker des types.
    Plutôt que de réinventer la roue, je suis tombé sur TTypeKind dans System (utilisé dans TypInfo).
    Ça avait l'air bien, jusqu'à ce que je me rende compte qu'il n'y a pas le type Booléen dans la liste !
    C'est moi qui passe à côté de quelque chose, ou ... ?
    C'est quand même un type de base, non ?
    (à côté de ça, y a tous plein de types chaines)

  2. #2
    Expert confirmé
    Avatar de popo
    Homme Profil pro
    Analyste programmeur Delphi / C#
    Inscrit en
    Mars 2005
    Messages
    2 759
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Analyste programmeur Delphi / C#
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mars 2005
    Messages : 2 759
    Points : 5 482
    Points
    5 482
    Par défaut
    Le booléen est de type tkEnumeration.

    Si tu as un record de type PTypeInfo tu peux aller chercher toutes les infos dont tu as besoin de cette manière
    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
     TypeData : PTypeData;
        PropList : TPropList;
        PropInfo : TPropInfo;
        PropKind : TTypeKind;
     
        PropName : String;
        PropType : String;
    begin
       TypeData := GetTypeData(TypeInfo);
       PropCount := TypeData.PropCount;
       if (PropCount > 0) then
       begin
         GetPropList(TypeInfo, tkAny, @PropList);
         for i := 0 to PropCount - 1 do
         begin
           PropInfo := PropList[i]^;
           PropName := PropInfo.Name;
           PropKind := PropInfo.PropType^.Kind;
           PropType := PropInfo.PropType^.Name;
     
            // Ici un booléen aura le PropKind à tkEnumeration
            // et le PropType à Boolean
         end; 
       end;
    end;

  3. #3
    Expert éminent sénior
    Avatar de ShaiLeTroll
    Homme Profil pro
    Développeur C++\Delphi
    Inscrit en
    Juillet 2006
    Messages
    13 665
    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 665
    Points : 25 459
    Points
    25 459
    Par défaut
    Si si cela existe

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    //------------------------------------------------------------------------------
    function TSLTPersistentORMEntityPropertyMetaData.KindTypeToFieldType(AKindType: TTypeKind; APropInfo: PPropInfo): TFieldType;
    begin
      Result := ftUnknown;
      if (AKindType = tkEnumeration) and (TSTLTypInfoRTTIWrapper.GetPropertyTypeData(APropInfo)^.BaseType^ = TypeInfo(Boolean)) then
      begin
        Result := ftBoolean;
      end
      else
        case AKindType of
          tkInteger: Result := ftInteger;
          tkUString: Result := ftString;
        end;
    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
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523
    524
    525
    526
    527
    528
    529
    530
    531
    532
    533
    534
    535
    536
    537
    538
    539
    540
    541
    //------------------------------------------------------------------------------
    (*                SoLuTions is an Versatile Library for Delphi                 -
     *                                                                             -
     *  Version alternative publiée sur "www.developpez.net"                       -
     *  Post : "récupérer les "properties" d'un objet"                             -
     *  Post Number : 4701588                                                      -
     *  Post URL = "http://www.developpez.net/forums/d819342/environnements-developpement/delphi/composants-vcl/recuperer-properties-d-objet/#post4701588"
     *                                                                             -
     *  Version C++ alternative publiée sur "www.developpez.net"                   -
     *  Post : "Copier les données d'un objet dans un autre"                       -
     *  Post Number : 6750404                                                      -
     *  Post URL = "http://www.developpez.net/forums/d1234651/environnements-developpement/delphi/langage/copier-donnees-d-objet/#post6750404"
     *                                                                             -
     *  Copyright "SLT Solutions", (©2006)                                         -
     *  contributeur : ShaiLeTroll (2012) - Renommage Fichier et Correction XE2    -
     *  contributeur : ShaiLeTroll (2012) - Documentation Insight                  -
     *  contributeur : ShaiLeTroll (2013) - Fusion de la SLT<2006> sous Delphi 7, SLT<2009> sous C++Builder 2007, SLT<2012> sous C++Builder XE2/XE3 vers la SLT<2013> sous Delphi XE2
     *                                                                             -
     *                                                                             -
     * Ce logiciel est un programme informatique servant à aider les développeurs  -
     * Delphi avec une bibliothèque polyvalente, adaptable et fragmentable.        -
     *                                                                             -
     * Ce logiciel est régi par la licence CeCILL-C soumise au droit français et   -
     * respectant les principes de diffusion des logiciels libres. Vous pouvez     -
     * utiliser, modifier et/ou redistribuer ce programme sous les conditions      -
     * de la licence CeCILL-C telle que diffusée par le CEA, le CNRS et l'INRIA    -
     * sur le site "http://www.cecill.info".                                       -
     *                                                                             -
     * En contrepartie de l'accessibilité au code source et des droits de copie,   -
     * de modification et de redistribution accordés par cette licence, il n'est   -
     * offert aux utilisateurs qu'une garantie limitée.  Pour les mêmes raisons,   -
     * seule une responsabilité restreinte pèse sur l'auteur du programme,  le     -
     * titulaire des droits patrimoniaux et les concédants successifs.             -
     *                                                                             -
     * A cet égard  l'attention de l'utilisateur est attirée sur les risques       -
     * associés au chargement,  à l'utilisation,  à la modification et/ou au       -
     * développement et à la reproduction du logiciel par l'utilisateur étant      -
     * donné sa spécificité de logiciel libre, qui peut le rendre complexe à       -
     * manipuler et qui le réserve donc à des développeurs et des professionnels   -
     * avertis possédant  des  connaissances  informatiques approfondies.  Les     -
     * utilisateurs sont donc invités à charger  et  tester  l'adéquation  du      -
     * logiciel à leurs besoins dans des conditions permettant d'assurer la        -
     * sécurité de leurs systèmes et ou de leurs données et, plus généralement,    -
     * à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.          -
     *                                                                             -
     * Le fait que vous puissiez accéder à cet en-tête signifie que vous avez      -
     * pris connaissance de la licence CeCILL-C, et que vous en avez accepté les   -
     * termes.                                                                     -
     *                                                                             -
     *----------------------------------------------------------------------------*)
    unit SLT.Common.RTTI;
     
    interface
     
    uses
      System.SysUtils, System.Classes, System.TypInfo;
     
    type
      { Forward class declarations }
      TSTLTypInfoRTTIWrapper = class;
      TSTLTypInfoRTTISimpleAccess = class;
      TSTLComponentStreaming = class;
     
      /// <summary>Classe qui encapsule les fonctions RTTI de TypInfo pour faciliter leur utilisation</summary>
      /// <remarks>Ne déclarez pas les variables de type TSTLRTTITypInfoReader, puisque TSTLRTTITypInfoReader n'a pas de champs ou de méthodes d'instance<remarks>
      TSTLTypInfoRTTIWrapper = class(TObject)
      public
        /// <summary>renvoie dans une TStrings préalablement instanciée, la Liste de propriétés publiées d'une Instance</summary>
        /// <param name="Instance">Contient l'Instance héritée de TPersistent à analyser</param>
        /// <param name="List">TStrings instanciée qui accueillera la liste des propriétés</param>
        /// <returns>Indique si la Fonction a trouvé au moins une propriété</returns>
        class function GetPersistentProperties(Instance: TObject; List: TStrings): Boolean; overload;
        /// <summary>renvoie dans une TStrings préalablement instanciée, la Liste de propriétés publiées d'une Classe de TPersistent ou de TObject compilé en $M+ ou {$TYPEINFO ON}</summary>
        /// <param name="AClass">Contient la Référence Classe héritée de TPersistent à analyser</param>
        /// <param name="List">TStrings instanciée qui accueillera la liste des propriétés</param>
        /// <param name="PersistentOnly">PersistentOnly indique si l'on vérifie que la AClass hérite au moins de TPersistent, cela est conseillé mais peut être désactivée si la classe AClass a été compilée avec la directive $M+</param>
        /// <returns>Indique si la Fonction a trouvé au moins une propriété</returns>
        class function GetPersistentProperties(AClass: TClass; List: TStrings; PersistentOnly: Boolean = True): Boolean; overload;
        /// <summary>IsPublishedProperty vérifie si la Classe possède cette propriété</summary>
        class function IsPublishedProperty(AClass: TClass; const PropertyName: string): Boolean;
        /// <summary>GetPropertyInfo utilise le système RTTI (Informations de type à l'exécution) de Delphi pour récupérer un pointeur sur l'enregistrement des informations d'une propriété publiée d'un objet compilé en $M+ ou {$TYPEINFO ON}.</summary>
        class function GetPropertyInfo(AClass: TClass; const PropertyName: string): PPropInfo; inline;
        /// <summary>Renvoie le nom d'une propriété de composant identifiée par un PPropInfo donné.</summary>
        class function GetPropertyName(APropertyInfo: PPropInfo): string; inline;
        /// <summary>GetPropertyTypeData utilise le système RTTI (Informations de type à l'exécution) de Delphi pour renvoyer un pointeur sur l'enregistrement TTypeData correspondant au type d'une propriété publiée d'un objet compilé en $M+ ou {$TYPEINFO ON}.</summary>
        class function GetPropertyTypeData(AClass: TClass; const PropertyName: string): PTypeData; overload; inline;
        /// <summary>GetPropertyTypeData utilise le système RTTI (Informations de type à l'exécution) de Delphi pour renvoyer un pointeur sur l'enregistrement TTypeData correspondant au type d'une propriété publiée d'un objet compilé en $M+ ou {$TYPEINFO ON}.</summary>
        class function GetPropertyTypeData(APropertyInfo: PPropInfo): PTypeData; overload; inline;
        /// <summary>Renvoie le nom d'une constante de type énuméré Delphi à partir de sa valeur.</summary>
        class function EnumToString(TypeInfo: PTypeInfo; Value: Integer): string;
        /// <summary>Renvoie la valeur d'une constante de type énuméré à partir de sa représentation sous forme de chaîne.</summary>
        class function StringToEnum(TypeInfo: PTypeInfo; const Name: string): Integer;
        /// <summary>Renvoie le type de la classe d'une propriété publiée si celle en est une</summary>
        class function TryGetPropertyClassType(Instance: TObject; const PropertyName: string; out APropertyClassType: TClass): Boolean; overload;
        /// <summary>Renvoie le type de la classe d'une propriété publiée si celle en est une</summary>
        class function TryGetPropertyClassType(AClass: TClass; const PropertyName: string; out APropertyClassType: TClass): Boolean; overload;
      end;
     
      /// <summary>Classe qui encapsule les fonctions RTTI de TypInfo pour faciliter leur utilisation</summary>
      TSTLTypInfoRTTISimpleAccess = class(TObject)
      private
        // Membres privés
        FInstance: TObject;
      protected
        // Accesseurs
        function GetInstance(): TObject;
        procedure SetInstance(const Value: TObject);
        function GetValue(const PropertyName: string): Variant;
        procedure SetValue(const PropertyName: string; const Value: Variant);
      public
        // Constructeurs
        constructor Create(const AInstance: TObject = nil);
     
        // Propriétés
        /// <summary>Indique l'instance d'objet contenant les propriétés publiées accessibles via RTTI</summary>
        property Instance: TObject read GetInstance write SetInstance;
        /// <summary>Accès directe à la valeur liée à une propriété publiée via RTTI/summary>
        property Values[const PropertyName: string]: Variant read GetValue write SetValue;
      end;
     
      /// <summary>Classe qui encapsule des manipulation sur les composants et leurs propriétés avec des flux.</summary>
      /// <remarks>Inspiré de l'exemple ComponentToString\StringToComponent de l'aide de Delphi 6<remarks>
      TSTLComponentStreaming = class(TObject)
      public
        /// <summary>Transforme un composant en chaine selon le format "DFM Texte"</summary>
        class function ComponentToString(Component: TComponent): string;
        /// <summary>Restitue un composant depuis chaine contenant des données au format "DFM Texte"</summary>
        class function StringToComponent(const Value: string): TComponent; overload;
        /// <summary>Restitue dans un composant depuis chaine contenant des données au format "DFM Texte"</summary>
        class procedure StringToComponent(var Component: TComponent; const Value: string); overload;
         /// <summary>Transforme un composant en Flux selon le format "DFM Texte"</summary>
        class function ComponentToStream(Component: TComponent; AStream: TStream): Boolean;
        /// <summary>Restitue un composant depuis un Flux contenant des données au format "DFM Texte"</summary>
        class function StreamToComponent(AStream: TStream): TComponent; overload;
        /// <summary>Restitue dans un composant depuis Flux contenant des données au format "DFM Texte"</summary>
        class procedure StreamToComponent(var Component: TComponent; AStream: TStream); overload;
        /// <summary>Transforme un composant et le sérialise dans un fichier au format "DFM Texte"</summary>
        class function ComponentToFile(Component: TComponent; const AFileName: TFileName): Boolean;
        /// <summary>Restitue un composant depuis un fichier au format "DFM Texte"</summary>
        class function FileToComponent(const AFileName: TFileName): TComponent;
      end;
     
    implementation
     
    uses System.Variants;
     
    { TSTLRTTITypInfoReader }
     
    {* -----------------------------------------------------------------------------
    La Fonction GetPersistentProperties renvoie dans une TStrings préalablement instanciée, la Liste de propriétés publiées d'une Instance
    @param Instance Contient l'Instance héritée de TPersistent à analyser
    @param List TStrings instanciée qui accueillera la liste des propriétés
    @return Indique si la Fonction a trouvé au moins une propriété
    ------------------------------------------------------------------------------ }
    class function TSTLTypInfoRTTIWrapper.GetPersistentProperties(Instance: TObject; List: TStrings): Boolean;
    begin
      Result := GetPersistentProperties(Instance.ClassType, List);
    end;
     
    //------------------------------------------------------------------------------
    class function TSTLTypInfoRTTIWrapper.EnumToString(TypeInfo: PTypeInfo; Value: Integer): string;
    begin
      Result := System.TypInfo.GetEnumName(TypeInfo, Value);
    end;
     
    {* -----------------------------------------------------------------------------
    La Fonction GetPersistentProperties renvoie dans une TStrings préalablement instanciée, la Liste de propriétés publiées d'une Classe de TPersistent
    @param AClass Contient la Référence Classe héritée de TPersistent à analyser
    @param List TStrings instanciée qui accueillera la liste des propriétés
    @param PersistentOnly indique si l'on vérifie que la AClass hérite au moins de TPersistent, cela est conseillé mais peut peut être désactivée si la classe AClass a été compilée avec la directive $M+
    @return Indique si la Fonction a trouvé au moins une propriété
    @remark Algo Basé sur Classes.TWriter.WriteProperties
    @remark Je préfère gérer explicitement la mémoire avec GetMem\FreeMem plutôt que d'utiliser GetPropList() qui alloue la mémoire alors que la documentation ne précise pas si l'appelant est responsable de la libération et encore moins la méthode de libération la plus appropriée !
    ------------------------------------------------------------------------------ }
    class function TSTLTypInfoRTTIWrapper.GetPersistentProperties(AClass: TClass; List: TStrings; PersistentOnly: Boolean = True): Boolean;
    var
      I, Count: Integer;
      PropInfo: PPropInfo;
      PropList: PPropList;
    begin
      Result := False;
      if Assigned(List) and Assigned(AClass) and (not PersistentOnly or (PersistentOnly and AClass.InheritsFrom(TPersistent))) then
      begin
        List.Clear();
        // Obtention du Nombre de Propriété de l'Instance
        Count := System.TypInfo.GetTypeData(AClass.ClassInfo)^.PropCount;
        if Count > 0 then
        begin
          // Allocation de la mémoire utilisée par la TStrings en prévision de l'ajout des noms de propriétés
          List.Capacity := Count;
     
          // Allocation de la mémoire pour la Liste des Propriétés de l'Instance
          GetMem(PropList, Count * SizeOf(Pointer));
          try
            // Récupération du Tableur de Pointeur décrivant les Propriétés de l'Instance
            System.TypInfo.GetPropInfos(AClass.ClassInfo, PropList);
            for I := 0 to Count - 1 do
            begin
              // Récupération du Ieme Element décrivant l'une des Propriétés de l'Instance
              PropInfo := PropList^[I];
              // Ajout du Nom de l'une des Propriétés de l'Instance
              if Assigned(PropInfo) then
                List.Add(System.TypInfo.GetPropName(PropInfo));
            end;
     
            // Retourne True si l'on a trouvé au moins une propriété
            Result := List.Count > 0;
          finally
            // Libération de la mémoire pour la Liste des Propriétés de l'Instance
            FreeMem(PropList, Count * SizeOf(Pointer));
          end;
        end;
      end;
    end;
     
    //------------------------------------------------------------------------------
    class function TSTLTypInfoRTTIWrapper.GetPropertyInfo(AClass: TClass; const PropertyName: string): PPropInfo;
    begin
      Result := System.TypInfo.GetPropInfo(AClass, PropertyName);
    end;
     
    //------------------------------------------------------------------------------
    class function TSTLTypInfoRTTIWrapper.GetPropertyName(APropertyInfo: PPropInfo): string;
    begin
      Result := System.TypInfo.GetPropName(APropertyInfo);
    end;
     
    //------------------------------------------------------------------------------
    class function TSTLTypInfoRTTIWrapper.GetPropertyTypeData(AClass: TClass; const PropertyName: string): PTypeData;
    begin
      Result := GetPropertyTypeData(GetPropertyInfo(AClass, PropertyName));
    end;
     
    //------------------------------------------------------------------------------
    class function TSTLTypInfoRTTIWrapper.GetPropertyTypeData(APropertyInfo: PPropInfo): PTypeData;
    begin
      Result := System.TypInfo.GetTypeData(APropertyInfo^.PropType^);
    end;
     
    {* -----------------------------------------------------------------------------
    La Fonction IsPublishedProperty vérifie si la Classe possède cette propriété
    @param PropertyName Nom de la Propriété Publiée
    @return Renvoie True si la Propriété est Publiée
    ------------------------------------------------------------------------------ }
    class function TSTLTypInfoRTTIWrapper.IsPublishedProperty(AClass: TClass; const PropertyName: string): Boolean;
    begin
      try
        Result := IsPublishedProp(AClass, PropertyName);
      except
        Result := False;
      end;
    end;
     
    //------------------------------------------------------------------------------
    class function TSTLTypInfoRTTIWrapper.StringToEnum(TypeInfo: PTypeInfo; const Name: string): Integer;
    begin
      Result := System.TypInfo.GetEnumValue(TypeInfo, Name);
    end;
     
    //------------------------------------------------------------------------------
    class function TSTLTypInfoRTTIWrapper.TryGetPropertyClassType(Instance: TObject; const PropertyName: string; out APropertyClassType: TClass): Boolean;
    begin
      if Assigned(Instance) then
        Result := TryGetPropertyClassType(Instance.ClassType, PropertyName, APropertyClassType)
      else
        Result := False;
    end;
     
    //------------------------------------------------------------------------------
    class function TSTLTypInfoRTTIWrapper.TryGetPropertyClassType(AClass: TClass; const PropertyName: string; out APropertyClassType: TClass): Boolean;
    var
      PropInfo: PPropInfo;
      PropTypeData: PTypeData;
    begin
      Result := False;
     
      if Assigned(AClass) then
      begin
        PropInfo := System.TypInfo.GetPropInfo(AClass, PropertyName);
     
        if Assigned(PropInfo) and (PropInfo^.PropType^^.Kind = tkClass) then
        begin
          PropTypeData := GetPropertyTypeData(PropInfo);
          if Assigned(PropTypeData) then
          begin
            Result := Assigned(PropTypeData.ClassType);
            APropertyClassType := PropTypeData.ClassType;
          end;
        end;
      end;
    end;
     
    { TSTLTypInfoRTTISimpleAccess }
     
    //------------------------------------------------------------------------------
    constructor TSTLTypInfoRTTISimpleAccess.Create(const AInstance: TObject = nil);
    begin
      inherited Create();
     
      FInstance := AInstance;
    end;
     
    //------------------------------------------------------------------------------
    function TSTLTypInfoRTTISimpleAccess.GetInstance(): TObject;
    begin
      Result := FInstance;
    end;
     
    //------------------------------------------------------------------------------
    function TSTLTypInfoRTTISimpleAccess.GetValue(const PropertyName: string): Variant;
    var
      PropInfo: PPropInfo;
    begin
      if Assigned(FInstance) then
      begin
        PropInfo := System.TypInfo.GetPropInfo(FInstance, PropertyName);
     
        if Assigned(PropInfo) and Assigned(PropInfo.GetProc) then
          Result := System.TypInfo.GetPropValue(FInstance, PropertyName, False)
      end;
    end;
     
    //------------------------------------------------------------------------------
    procedure TSTLTypInfoRTTISimpleAccess.SetInstance(const Value: TObject);
    begin
      FInstance := Value;
    end;
     
    //------------------------------------------------------------------------------
    procedure TSTLTypInfoRTTISimpleAccess.SetValue(const PropertyName: string; const Value: Variant);
    var
      PropInfo: PPropInfo;
    begin
      if Assigned(FInstance) then
      begin
        PropInfo := System.TypInfo.GetPropInfo(FInstance, PropertyName);
     
        if Assigned(PropInfo) and Assigned(PropInfo.SetProc) then
          System.TypInfo.SetPropValue(FInstance, PropertyName, Value);
      end;
    end;
     
    { TSTLComponentStreaming }
     
    {* -----------------------------------------------------------------------------
    La Fonction ComponentToFile écrit dans un fichier, le Component et ses propriétés publiées dans le format de Flux Delphi (cf dfm)
    @param Component Contient l'Instance héritée de TComponent à analyser
    @param AFileName Contient le nom du fichier a écrire
    @return Booléen indique que la sérialisation s'est effectué correctement
    Algo Basé sur l'exemple fourni avec ObjectBinaryToText et ObjectTextToBinary
    ------------------------------------------------------------------------------ }
    class function TSTLComponentStreaming.ComponentToFile(Component: TComponent; const AFileName: TFileName): Boolean;
    var
      FileStream: TFileStream;
      OpenMode: Word;
    begin
      Result := False;
     
      if not Assigned(Component) then
      begin
        DeleteFile(AFileName);
        Exit;
      end;
     
      if FileExists(AFileName) then
        OpenMode := fmOpenWrite
      else
        OpenMode := fmCreate;
     
      // Rien n'empêche les autres applications de lire ou d'écrire dans le fichier.
      FileStream := TFileStream.Create(AFileName, OpenMode or fmShareDenyNone);
      try
        Result := ComponentToStream(Component, FileStream);
      finally
        FileStream.Free();
      end;
    end;
     
    {* -----------------------------------------------------------------------------
    La Fonction ComponentToStream écrit dans un Flux, le Component et ses propriétés publiées dans le format de Flux Delphi (cf dfm)
    @param Component Contient l'Instance héritée de TComponent à analyser
    @param AStream Flux qui recevra la version Texte du Component
    @return Booléen indique que la sérialisation s'est effectué correctement
    Algo Basé sur l'exemple fourni avec ObjectBinaryToText et ObjectTextToBinary
    ------------------------------------------------------------------------------ }
    class function TSTLComponentStreaming.ComponentToStream(Component: TComponent; AStream: TStream): Boolean;
    var
      BinStream: TMemoryStream;
    begin
      BinStream := TMemoryStream.Create();
      try
        BinStream.WriteComponent(Component);
        BinStream.Seek(0, soFromBeginning);
        ObjectBinaryToText(BinStream, AStream);
        Result := AStream.Size >= BinStream.Size;
      finally
        BinStream.Free()
      end;
    end;
     
    {* -----------------------------------------------------------------------------
    La Fonction ComponentToString renvoie dans une String, le Component et ses propriétés publiées dans le format de Flux Delphi (cf dfm)
    @param Component Contient l'Instance héritée de TComponent à analyser
    @return Chaine contenant la version Texte du Component
    Algo Basé sur l'exemple fourni avec ObjectBinaryToText et ObjectTextToBinary
    ------------------------------------------------------------------------------ }
    class function TSTLComponentStreaming.ComponentToString(Component: TComponent): string;
    var
      StrStream: TStringStream;
    begin
      if not Assigned(Component) then
      begin
        Result := '';
        Exit;
      end;
     
      StrStream := TStringStream.Create();
      try
        ComponentToStream(Component, StrStream);
        StrStream.Seek(0, soFromBeginning);
        Result := StrStream.DataString;
      finally
        StrStream.Free();
      end;
    end;
     
    {* -----------------------------------------------------------------------------
    La Fonction FileToComponent prend dans un fichier, le Component et ses propriétés publiées dans le format de Flux Delphi (cf dfm)
    @param AFileName Contient le nom du fichier à lire
    @return Contient l'Instance héritée de TComponent instancié via le Flux
    Algo Basé sur l'exemple fourni avec ObjectBinaryToText et ObjectTextToBinary
    ------------------------------------------------------------------------------ }
    class function TSTLComponentStreaming.FileToComponent(const AFileName: TFileName): TComponent;
    const
      MIN_FILE_SIZE = Length('object : T..end');
    var
      FileStream: TFileStream;
    begin
      Result := nil;
     
      if (AFileName = '') or not FileExists(AFileName) then
        Exit;
     
      // Les autres applications peuvent ouvrir le fichier en lecture, mais pas en écriture !
      FileStream := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyWrite);
      try
        // le Fichier doit au mois contenir "object : T..end"
        if FileStream.Size > MIN_FILE_SIZE then
          Result := StreamToComponent(FileStream);
      finally
        FileStream.Free();
      end;
    end;
     
    {* -----------------------------------------------------------------------------
    La Fonction StringToComponent prend dans une String, le Component et ses propriétés publiées dans le format de Flux Delphi (cf dfm)
    @param Value est une chaine contenant la version Texte du Component
    @return Contient l'Instance héritée de TComponent instancié via le Flux
    Algo Basé sur l'exemple fourni avec ObjectBinaryToText et ObjectTextToBinary
    ------------------------------------------------------------------------------ }
    class function TSTLComponentStreaming.StringToComponent(const Value: string): TComponent;
    var
      StrStream: TStringStream;
    begin
      if Value = '' then
      begin
        Result := nil;
        Exit;
      end;
     
      StrStream := TStringStream.Create(Value);
      try
        Result := StreamToComponent(StrStream);
      finally
        StrStream.Free();
      end;
    end;
     
    {* -----------------------------------------------------------------------------
    La Fonction StreamToComponent prend dans un Flux, le Component et ses propriétés publiées dans le format de Flux Delphi (cf dfm)
    @param Component est l'Instance héritée de TComponent à instancier via le Flux
    @return Contient l'Instance héritée de TComponent instancié via le Flux
    Algo Basé sur l'exemple fourni avec ObjectBinaryToText et ObjectTextToBinary
    ------------------------------------------------------------------------------ }
    class function TSTLComponentStreaming.StreamToComponent(AStream: TStream): TComponent;
    var
      BinStream: TMemoryStream;
    begin
      BinStream := TMemoryStream.Create();
      try
        ObjectTextToBinary(AStream, BinStream);
        BinStream.Seek(0, soFromBeginning);
        Result := BinStream.ReadComponent(nil);
      finally
        BinStream.Free();
      end;
    end;
     
    {* -----------------------------------------------------------------------------
    La Fonction StreamToComponent prend dans un Flux, le Component et ses propriétés publiées dans le format de Flux Delphi (cf dfm)
    @param Component est l'Instance héritée de TComponent à instancier via le Flux
    @param Value est un Flux contenant la version Texte du Component
    Algo Basé sur l'exemple fourni avec ObjectBinaryToText et ObjectTextToBinary
    ------------------------------------------------------------------------------ }
    class procedure TSTLComponentStreaming.StreamToComponent(var Component: TComponent; AStream: TStream);
    var
      BinStream: TMemoryStream;
    begin
      BinStream := TMemoryStream.Create();
      try
        ObjectTextToBinary(AStream, BinStream);
        BinStream.Seek(0, soFromBeginning);
        BinStream.ReadComponent(Component);
      finally
        BinStream.Free();
      end;
    end;
     
    {* -----------------------------------------------------------------------------
    La Fonction StringToComponent prend dans une String, le Component et ses propriétés publiées dans le format de Flux Delphi (cf dfm)
    @param Component est l'Instance héritée de TComponent à instancier via le Flux
    @param Value est une Chaine contenant la version Texte du Component
    Algo Basé sur l'exemple fourni avec ObjectBinaryToText et ObjectTextToBinary
    ------------------------------------------------------------------------------ }
    class procedure TSTLComponentStreaming.StringToComponent(var Component: TComponent; const Value: string);
    var
      StrStream: TStringStream;
    begin
      if Value = '' then
        Exit;
     
      StrStream := TStringStream.Create(Value);
      try
        StreamToComponent(Component, StrStream);
      finally
        StrStream.Free();
      end;
    end;
     
     
    end.

    ou encore

    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
    {* -----------------------------------------------------------------------------
    La Fonction SetPropertyValue prend dans une Variable la Valeur Variant qui sera affectée à la propriété publiée sous le nom de PropertyName
    @param Instance Contient l'Instance héritée de TPersistent à analyser
    @param PropertyName Indique la Propriété à affecter
    @param Value Variable qui fourni la nouvelle Valeur de la propriété publiée
    @param PropertyVarType indique le Type le Propriété pour les Forcer les Conversions
    @return Indique si la Fonction a trouvé la propriété
    ------------------------------------------------------------------------------ }
    class function TEpcRTTIWrapper.SetPropertyValue(Instance: TPersistent; const PropertyName: string; const Value: Variant; const PropertyVarType: TVarType = varVariant): Boolean;
    var
      PropInfo: PPropInfo;
      TypeValue: Integer;
     
      procedure RaisePropertyConvertError();
      var
        SConvIncompatibleTypes2Ex: string;
      begin
        SConvIncompatibleTypes2Ex := 'Classe %s, Propriétés %s : ' + SConvIncompatibleTypes2;
        raise EPropertyConvertError.CreateFmt(SConvIncompatibleTypes2Ex, [Instance.ClassName, PropertyName, VarTypeAsText(VarType(Value)), GetEnumName(TypeInfo(TTypeKind), Ord(PropInfo^.PropType^^.Kind))]);
      end;
     
    begin
      try
        PropInfo := GetPropInfo(Instance, PropertyName);
        Result := Assigned(PropInfo) and Assigned(PropInfo.SetProc);
        TypeValue := VarType(Value);
        if Result then
        begin
          case PropInfo.PropType^.Kind of
            tkVariant     : {none};
            tkInteger     : if not (TypeValue in [varWord, varByte, varShortInt, varSmallInt, varInteger, varLongWord, varBoolean]) then RaisePropertyConvertError();
            tkEnumeration : if not (TypeValue = varString) and not (TypeValue = varBoolean) then RaisePropertyConvertError();
            tkFloat       : if not (TypeValue in [varSingle, varDouble, varCurrency, varDate]) then RaisePropertyConvertError();
            tkString      : if not (TypeValue = varString) then RaisePropertyConvertError();
            tkLString     : if not (TypeValue = varString) then RaisePropertyConvertError();
            tkWString     : if not (TypeValue = varString) then RaisePropertyConvertError();
            tkInt64       : if not (TypeValue in [varInt64, varWord, varByte, varShortInt, varSmallInt, varInteger, varLongWord, varBoolean]) then RaisePropertyConvertError();
            else
              raise EPropertyError.CreateFmt(SInvalidPropertyType, [GetEnumName(TypeInfo(TTypeKind), Ord(PropInfo^.PropType^^.Kind))]);
           end;
     
           if (TypeValue = varString) and ((PropertyVarType = varBoolean) or ((PropInfo^.PropType^^.Kind = tkEnumeration) and (GetTypeData(PropInfo^.PropType^)^.BaseType^ = TypeInfo(Boolean)))) then
             if PropertyVarType = varBoolean then
               SetPropValue(Instance, PropertyName, StrToBool(LocalToSystemStrBool(Value)))
             else
               SetPropValue(Instance, PropertyName, LocalToSystemStrBool(Value))
           else
             SetPropValue(Instance, PropertyName, Value);
        end;
      except
        on epe: EPropertyError do
        begin
          Result := False;
          ManagePropertyError(adSet, epe, PropertyName);
        end else
          raise;
      end;
    end;

  4. #4
    Expert éminent
    Avatar de Lung
    Profil pro
    Analyste-programmeur
    Inscrit en
    Mai 2002
    Messages
    2 678
    Détails du profil
    Informations personnelles :
    Âge : 44
    Localisation : France, Haute Savoie (Rhône Alpes)

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

    Informations forums :
    Inscription : Mai 2002
    Messages : 2 678
    Points : 7 093
    Points
    7 093
    Par défaut
    Ah ok.
    J'étais loin de penser à l'énumération (à la rigueur, un entier ...).
    pour les explications. Je vais potasser tout ça ...

  5. #5
    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 : 55
    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 457
    Points
    28 457
    Par défaut
    oui, je trouve qu'il manque quelques types, je me suis déclaré un nouvel énuméré pour ça

    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
     
      TExtendedType = (
        etUnknown,       // tkUnknown,
        etLongInt,       // tkInteger
        etAnsiChar,      // tkChar
        etEnum8,         // tkEnumaration -> etEnum16, etEnum32
        etSingle,        // tkFloat -> etDateTime, etDate, etTime, etSingle, etDouble, etExtended, etCurrency
        etShortString,   // tkString -> etSizedString
        etSet8,          // tkSet -> etSet16, etSet32
        etClass,         // tkClasse
        etMethod,        // tkMethod
        etWideChar,      // tkWChar
        etAnsiString,    // tkLString
        etWideString,    // tkWString
        etVariant,       // tkVariant
        etArray,         // tkArray
        etRecord,        // tkRecord
        etInterface,     // tkInterface
        etInt64,         // tkInt64 -> etUInt64
        etDynArray,      // tkDynArray
        etString,        // tkUString
        etClassRef,      // tkClassRef
        etPointer,       // tkPointer
        etProcedure,     // tkProcedure
        etManagedRecord, // tkMRecord
        etNone,          // ---> first Extended types
      // tkInteger
        etShortInt,
        etByte,
        etSmallInt,
        etWord,
        etCardinal,
      // tkEnumaration
        etEnum16,
        etEnum32,
      // tkFloat
        etDateTime,
        etDate,
        etTime,
        etDouble,
        etExtended,
        etComp,
        etCurrency,
      // tkString
        etSizedString,
        etBoolean,
      // tkSet
        etSet16,
        etSet32,
      // tkInt64
        etUInt64
      );
     
    function TTypeInfoHelper.ExtendedType: TExtendedType;
    begin
      if @Self = nil then
        Result := etNone
      else
      case Kind of
        tkUnknown : Result := etUnknown;
        tkInteger :
          case TypeData.OrdType of
            otSByte: Result := etShortInt;
            otUByte: Result := etByte;
            otSWord: Result := etSmallInt;
            otUWord: Result := etWord;
            otSLong: Result := etLongInt;
            otULong: Result := etCardinal;
          end;
        tkChar: Result := etAnsiChar;
        tkEnumeration :
          case TypeData.OrdType of
            otSByte,
            otUByte: Result := etEnum8;
            otSWord,
            otUWord: Result := etEnum16;
            otSLong,
            otULong: Result := etEnum32;
          end;
        tkFloat:
          begin
            if @Self = System.TypeInfo(TDateTime) then
              Result := etDateTime
            else
            if @Self = System.TypeInfo(TDate) then
              Result := etDate
            else
            if @Self = System.TypeInfo(TTime) then
              Result := etTime
            else
            case TypeData.FloatType of
              ftSingle   : Result := etSingle;
              ftDouble   : Result := etDouble;
              ftExtended : Result := etExtended;
              ftComp     : Result := etComp;
              ftCurr     : Result := etCurrency;
            end;
          end;
        tkString:
          if TypeData.MaxLength = 255 then
            Result := etShortString
          else
            Result := etSizedString;
        tkSet:
          begin
            if @Self = System.TypeInfo(Boolean) then
              Result := etBoolean
            else
            case TypeData.OrdType of
              otSByte,
              otUByte: Result := etSet8;
              otSWord,
              otUWord: Result := etSet16;
              otSLong,
              otULong: Result := etSet32;
            end;
          end;
        tkClass: Result := etClass;
        tkMethod: Result := etMethod;
        tkWChar: Result := etWideChar;
        tkLString: Result := etAnsiString;
        tkWString: Result := etWideString;
        tkVariant: Result := etVariant;
        tkArray: Result := etArray;
        tkRecord: Result := etRecord;
        tkInterface: Result := etInterface;
        tkInt64:
          if TypeData.MinInt64Value = 0 then
            Result := etUInt64
          else
            Result := etInt64;
        tkDynArray: Result := etDynArray;
        tkUString: Result := etString;
        tkClassRef: Result := etClassRef;
        tkPointer: Result := etPointer;
        tkProcedure: Result := etProcedure;
      {$IF CompilerVersion >= 33.0} // Rio
        tkMRecord: Result := etManagedRecord;
      {$ENDIF}
      else
        Result := etNone;
      end;
    end;

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

Discussions similaires

  1. Pourquoi pas de variable dans SELECT ?
    Par alassanediakite dans le forum Langage SQL
    Réponses: 22
    Dernier message: 22/06/2017, 15h31
  2. Pourquoi pas de Java dans les JSP
    Par Kurogane dans le forum Servlets/JSP
    Réponses: 7
    Dernier message: 09/10/2013, 17h17
  3. Pourquoi pas de "cascading" dans cet exemple ?
    Par allweneed dans le forum Mise en page CSS
    Réponses: 3
    Dernier message: 10/04/2012, 14h04
  4. [XL-2003] pourquoi excel ne me laisse pas ecrire "nu" dans une case
    Par micamused dans le forum Excel
    Réponses: 1
    Dernier message: 17/11/2010, 12h59
  5. [SERVER] Pourquoi pas de make dans mac os x server 10.4.9
    Par Khaled.Noordin dans le forum Développement OS X
    Réponses: 2
    Dernier message: 29/05/2007, 16h55

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