是否有可能并且如何在运行时创建和附加自定义属性到字段上?
uses
System.SysUtils,
System.Classes,
System.Rtti;
type
MyAttribute = class(TCustomAttribute)
private
fCaption: string;
public
constructor Create(const aCaption: string);
property Caption: string read fCaption write fCaption;
end;
TFoo = class(TPersistent)
public
[MyAttribute('Title')]
Bar: string;
Other: string;
end;
constructor MyAttribute.Create(const aCaption: string);
begin
fCaption := aCaption;
end;
procedure CreateAttributes(Typ: TRttiType);
var
Field: TRttiField;
MyAttr: MyAttribute;
begin
for Field in Typ.GetFields do
begin
if Length(Field.GetAttributes) = 0 then
begin
MyAttr := MyAttribute.Create('Empty');
// how to attach created attribute to Field ???
end;
end;
end;
var
Context: TRttiContext;
Typ: TRttiType;
Field: TRttiField;
Attr: TCustomAttribute;
begin
Context := TRttiContext.Create;
Typ := Context.GetType(TFoo);
CreateAttributes(Typ);
for Field in Typ.GetFields do
for Attr in Field.GetAttributes do
if Attr is MyAttribute then
writeln(Field.Name + ' ' + MyAttribute(Attr).Caption);
readln;
Context.Free;
end.
运行上面的代码会产生输出:
Bar Title
我希望在运行时向没有赋值的字段注入带有值
Empty
的MyAttribute
,并产生以下输出结果:Bar Title
Other Empty