Where are the Delphi Attributes Real World Examples?

后端 未结 3 1817
刺人心
刺人心 2021-02-04 08:45

I know by TMS Aurelius that we can use the \"new\" 2010 attributes feature to serialize database table fields into object properties at run-time, for example, and I am not an ex

3条回答
  •  旧时难觅i
    2021-02-04 09:14

    I must say it's not much clear to me what kind of example do you need. IMHO in http://docwiki.embarcadero.com/RADStudio/Rio/en/Overview_of_Attributes is everything you should need, perhaps providing that you have some basic knowledge of annotation and/or aspect programming resp.

    An example depends on the way/purpose an author of particular SW used attributes for. You mentioned the ORM system: the typical usage here is to annotate member of the class representing DB entity with additional information necessary for DB operation in the backend of such framework. Let assume you have a DB entity having field COMPANY CHAR(32) NOT NULL and you want to represent it in Delphi class:

    TSomeDBEntity = class(...)
      FCDS: TClientDataset;
      ...
      constructor Create;
      ... 
      [TCharColumn('COMPANY', 32, false)]
      property CompanyName: string read GetCompanyName write SetCompanyName;
    end;
    

    then you will define attribute TCharColumn with constructor

    constructor TCharColumn.Create(const AFieldName:string; ALength:integer; ANullable:boolean);
    begin
      inherited;
      FName := AFieldName;
      FLength := ALength;
      FNullable := ANullable;
    end;
    

    And usage of such annotation could look something like this:

    FCDS := TClientDataset.Create(nil);
    RttiContext := TRttiContext.Create;
    try
      RttiType := RttiContext.GetType(self.ClassType);
      Props := RttiType.GetProperties;
      for Prop in Props do
        begin
          Attrs := Prop.GetAttributes;
          case Prop.PropertyType.TypeKind of
            tkUString:
              begin
                for Attr in Attrs do
                  if Attr is TCharColumn then
                  begin
                    ColAttr := TCharColumn(Attr);
                    FCDS.FieldDefs.Add(ColAttr.FName, ftString, ColAttr.FLength, not ColAttr.FNullable);
                  end;
              end;
            else
              //... ;
          end;
        end;
    finally
      RttiContext.Free;
    end;
    

    This piece of the program demonstrates, how to define fields in a dataset in run-time based on annotation in Delphi. We are limited little bit due lack of named parameters, hence working with parameter list is not flexible as should be e.g. like in Java (compare TMS Aurelius annotation set http://www.tmssoftware.com/site/manuals/aurelius_manual.pdf and http://www.techferry.com/articles/hibernate-jpa-annotations.html

提交回复
热议问题