我必须说我不太清楚你需要什么样的例子。恕我直言,在http://docwiki.embarcadero.com/RADStudio/Rio/en/Overview_of_Attributes http://docwiki.embarcadero.com/RADStudio/XE4/en/Overview_of_Attributes是您应该需要的一切,也许前提是您具有注释和/或方面编程的一些基本知识。
示例取决于特定软件的作者使用属性的方式/目的。您提到了ORM系统:这里的典型用法是用此类框架后端的数据库操作所需的附加信息来注释表示数据库实体的类的成员。假设您有一个数据库实体,其字段 COMPANY CHAR(32) NOT NULL 并且您希望在 Delphi 类中表示它:
TSomeDBEntity = class(...)
FCDS: TClientDataset;
...
constructor Create;
...
[TCharColumn('COMPANY', 32, false)]
property CompanyName: string read GetCompanyName write SetCompanyName;
end;
然后您将使用构造函数定义属性 TCharColumn
constructor TCharColumn.Create(const AFieldName:string; ALength:integer; ANullable:boolean);
begin
inherited;
FName := AFieldName;
FLength := ALength;
FNullable := ANullable;
end;
这种注释的用法可能如下所示:
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;
这段程序演示了如何在运行时基于 Delphi 中的注释定义数据集中的字段。由于缺乏命名参数,我们受到了一点限制,因此使用参数列表并不灵活,例如就像在 Java 中一样(比较 TMS Aurelius 注释集http://www.tmssoftware.com/site/manuals/aurelius_manual.pdf http://www.tmssoftware.com/site/manuals/aurelius_manual.pdf and http://www.techferry.com/articles/hibernate-jpa-annotations.html http://www.techferry.com/articles/hibernate-jpa-annotations.html