Where are the Delphi Attributes Real World Examples?

后端 未结 3 1808
刺人心
刺人心 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条回答
  •  迷失自我
    2021-02-04 08:57

    Not sure if the question is asking for real world examples of attribute use or how to serialize db tables into objects using attributes. The example below is a contrived simple one (but an example none the less) showing how to use attributes to log changes to object properties.

    Define your custom attribute

    //By convention attributes are *not* prefixed with a `T` 
    //and have the word `Attribute` in their name
    LoggableAttribute = class(TCustomAttribute)
      private
        FDescription : String;
      public
        constructor Create(Description: String);
        property Description: String read FDescription;
      end;
    

    The "hello world" of classes TProduct using the attribute

    TProduct = Class(TObject)
       private
        FPrice: Double;
        FDescription: String;
        ..
       public  
        [LoggableAttribute('Product Price')]
        property Price : Double read FPrice write SetPrice;
        [Loggable('Product Description')]   {the `Attribute` part is optional}
        property Description : String read FDescription write SetDescription;
        property IsDirty : Boolean read FIsDirty;
      End;
    

    Any class that has a "loggable attribute" can be passed to this method to iterate through the properties and log them.

    procedure LogChanges(LoggableClass: TObject);
    var
     c : TRttiContext;
     t : TRttiType;
     p : TRttiProperty;
     a : TCustomAttribute;
     Value : TValue;
    begin
     c := TRttiContext.Create;    
     try
       t := c.GetType(LoggableClass.ClassType);
       for p in t.getProperties do
         for a in p.GetAttributes do
           if a is TLoggableProperty then begin
             Value := p.GetValue(LoggableClass);   
             // log to db.. 
             AddLogEntry(p.Name, TLoggableProperty(a).Description, Value.ToString);
           end;
     finally
       c.Free;
     end;
    

    end;

    Example of use:

    var
     P : TProduct;
    begin    
     P := TProduct.Create; 
     P.LoadPropertiesFromDB;
     ...
     ... User edits price ...    
     ... 
     P.Price := 499.99;
     ...
     ... Save product to DB 
     if P.IsDirty then  // save and log
       LogChanges(P);
    

提交回复
热议问题