不确定问题是否要求提供属性使用的真实示例,或者如何使用属性将数据库表序列化为对象。下面的示例是一个人为的简单示例(但仍然是一个示例),展示了如何使用属性来记录对对象属性的更改。
定义您的自定义属性
//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;
使用属性的 TProduct 类的“hello world”
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;
任何具有“可记录属性”的类都可以传递给此方法以遍历属性并记录它们。
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;
结尾;
使用示例:
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);