Tuesday, July 11, 2017

Are you using Attributes?

Why not?  Too complicate? Not needed?


Let's take a look at this little stupid class:


  [ Bar(42) ]
  [ FooBar('Test') ]
  TFoo = class
    private
      [ FieldName('StringField') ]
      [ FieldLength(30) ]
      FField1 : String;
      [ FieldName('IntegerField') ]
      FField2 : Integer;
  end;



How can we get this Attribute-Values?

Over the RTTI of course...


What do you think about this approach:


  TRTTIHelper.OnClassHasAttributes( TFoo )
   {} .OnAttribute< BarAttribute >(
        procedure( Bar : BarAttribute )
          begin
            _Result1 := Bar.IntValue;
          end )
   {} .OnAttribute< FooBarAttribute >(
        procedure( FooBar : FooBarAttribute )
          begin
            _Result2 := FooBar.StrValue;
          end );



And the fields? Perhaps you prefer this:
  TRTTIHelper.OnFieldsHaveAttribute<FieldNameAttribute,FieldLengthAttribute>(TFoo,
 Procedure (Field : TRttiField; Attr : FieldNameAttribute)
   begin
     if Field.Name = 'FField2' then
       _Result2 := Attr.Value;
   end,

 Procedure (Field : TRttiField; Attr : FieldLengthAttribute)
   begin
     if Field.Name = 'FField1' then
       _Result1 := Attr.Value;
   end);



This Helper has many overloads like TProc<T1,T2,T3> from System.Sysutils,


Stay tuned for the next update of my FDK and just write:


Uses
  Delphiprofi.FDK.RTTI;




Remember:
Rule of Thumb: „Uses is faster than self-typing“!


No comments:

Post a Comment