如何在Delphi中在运行时创建自定义属性并将其附加到字段

Dal*_*kar 6 delphi attributes rtti

是否可以以及如何在运行时创建自定义属性并将其附加到字段?

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.
Run Code Online (Sandbox Code Playgroud)

在代码上运行会产生输出:

Bar Title
Run Code Online (Sandbox Code Playgroud)

我想为运行时没有它的字段注入MyAttributeEmpty,产生以下输出:

Bar Title
Other Empty
Run Code Online (Sandbox Code Playgroud)

Dav*_*nan 2

该框架没有提供在运行时附加属性的机制。任何这样做的尝试都将涉及破坏框架。