码农的笔记

Delphi虽好,但已不流行; 博客真好,可以做笔记

博客园 首页 新随笔 联系 订阅 管理

开发环境Delphi XE10

 

 

 

 

 

 1 unit Unit1;
 2 
 3 interface
 4 
 5 uses
 6   Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
 7   Vcl.Controls, Vcl.Forms, Vcl.Dialogs, System.RTTI, Vcl.StdCtrls;
 8 
 9 type
10   TForm1 = class(TForm)
11     Button1: TButton;
12     procedure Button1Click(Sender: TObject);
13   private
14     { Private declarations }
15   public
16     { Public declarations }
17   end;
18   type
19   TMyAttribute = class(TCustomAttribute)
20     private
21       FValue: string;
22     public
23        constructor Create(v: string); //带RTTI信息的Attributes时,必须要实现自定义的构造器
24       
25       property Value: string Read Fvalue Write FValue;
26    end;
27 //然后就可以用来注释了,简单的注释操作如下
28   [TMyAttribute('Msg')]
29   MyRec = record
30     R_str:string;
31   end;
32 var
33   Form1: TForm1;
34 
35 implementation
36 
37 {$R *.dfm}
38 function GetMyRecAttr: string;
39 var
40   LContext: TRttiContext;
41   LType: TRttiType;
42   LAttr: TCustomAttribute;
43 begin
44   LContext := TRTTIContext.Create; //创建上下文对象
45   LType := LContext.GetType(TypeInfo(MyRec));//获取MyRec的类型信息
46   try
47     for LAttr In LType.GetAttributes() do //遍历MyRec中的Attributes
48       if LAttr is TMyAttribute then
49         ShowMessage(TMyAttribute(LAttr).value);
50   except
51     ShowMessage('读取失败');
52   end;
53 end;
54 { TMyAttribute }
55 
56 constructor TMyAttribute.Create(v: string);
57 begin
58   FValue:='AAAAAAAAAAA+'+v;
59 end;
60 
61 procedure TForm1.Button1Click(Sender: TObject);
62 begin
63   GetMyRecAttr;
64 end;
65 
66 end.

 

 

 

 1 object Form1: TForm1
 2   Left = 0
 3   Top = 0
 4   Caption = 'Form1'
 5   ClientHeight = 130
 6   ClientWidth = 288
 7   Color = clBtnFace
 8   Font.Charset = DEFAULT_CHARSET
 9   Font.Color = clWindowText
10   Font.Height = -11
11   Font.Name = 'Tahoma'
12   Font.Style = []
13   OldCreateOrder = False
14   Position = poDesktopCenter
15   PixelsPerInch = 96
16   TextHeight = 13
17   object Button1: TButton
18     Left = 96
19     Top = 48
20     Width = 75
21     Height = 25
22     Caption = 'Button1'
23     TabOrder = 0
24     OnClick = Button1Click
25   end
26 end

 

posted on 2022-12-21 18:42  码农的笔记  阅读(144)  评论(0编辑  收藏  举报