-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTest.pas
More file actions
97 lines (88 loc) · 2.59 KB
/
Test.pas
File metadata and controls
97 lines (88 loc) · 2.59 KB
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
program Test;
{
This is a simple example on how to use custom attributes.
The class uses a custom attribute to retrieve a static date
at program start-up. This is just for the purpose of demo.
This demo's:
- Creation
- Decoration
- Retrieval
}
{$mode delphi}{$H+}{$M+}
{$warn 5079 off} { turn warning experimental off }
uses
sysutils, typinfo, rtti, classes;
type
{A custom attribute to decorate a class with a certain date }
ADateTimeAttribute = class(TCustomAttribute)
private
FArg:TDateTime;
public
{ Just to show a Custom Attribute can have mutiple constructors }
constructor Create(const aArg: TDateTime);overload;
{ We can use the predefined %DATE% compiler include
In the context of a custom attribute we need a
constant expression for the default parameter }
constructor Create(const aArg: String = {$I %DATE%});overload;
published
property Date:TDateTime read Farg;
end;
{ A datetime class that is decorated with our custom attribute }
{ Note you can leave out 'Attribute', the compiler resolves it }
{ [ADateTime(21237.0)] uses first constructor,displays some date in 1958 }
{This calls the second constructor }
[ADateTime]
TMyDateTimeClass = class
private
FDateTime:TDateTime;
public
constructor create;
published
[ADateTime]
property Day:TDateTime read FDatetime write FdateTime;
end;
constructor ADateTimeAttribute.Create(const aArg: TDateTime);
begin
FArg := aArg;
end;
constructor ADateTimeAttribute.Create(const aArg: string );
var
MySettings:Tformatsettings;
begin
{ set up the date format according to how
the compiler formats %DATE% include }
MySettings :=DefaultFormatSettings;
MySettings.ShortDateFormat:='yyyymmdd';
MySettings.DateSeparator :='/';
{ Now convert }
FArg := StrToDateTime(aArg, MySettings);
end;
{ We query the rtti to set the value }
constructor TMyDateTimeClass.Create;
var
Context : TRttiContext;
AType : TRttiType;
Attribute : TCustomAttribute;
begin
inherited;
Context := TRttiContext.Create;
try
AType := Context.GetType(typeinfo(TMyDateTimeClass));
for Attribute in AType.GetAttributes do begin
if Attribute is ADateTimeAttribute then
FDateTime := ADateTimeAttribute(Attribute).Date;
end;
finally
Context.Free
end;
end;
var
Test:TMyDateTimeClass;
begin
Test := TMyDateTimeClass.Create;
try
writeln('Compile date is :',DateTimeToStr(Test.Day));
finally
test.free;
end;
end.