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

达莉娅(Dalija Prasnikar)

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

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

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

Bar Title
Other Empty
戴维·赫弗南

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

创建可下载的自定义主题并在运行时应用

在运行时导出自定义EditorFormatDefinition

如何在运行时自定义XML中定义的自定义可绘制对象?

在.NET中在运行时合并自定义配置节

如何在MVC的运行时自定义显示和必需属性

如何从“自定义文本字段”调用值并将其动态放置在“表单属性”中?

如何在运行时将值添加到自定义维度-Azure应用程序见解

如何在Java中使用注释相关参数检查自定义运行时异常属性

如何在单击时在运行时为整个应用程序设置自定义主题?

在运行时将自定义窗口小部件添加到屏幕

如何在运行时自定义antd主题?

RealityKit如何在运行时创建自定义网格?

附加到正在运行的远程容器时如何使VSCode运行自定义脚本

如何在运行时创建新策略并将其附加到角色,而无需在代码资源中硬编码policy_document JSON?

我可以在运行时在Ormlite中构建自定义查询吗?

可以在运行时自定义FilterProvider吗?

如何在运行时使用Simple Injector添加注入的自定义验证属性?

如何在运行时更改自定义视图颜色?

如何在运行时将自定义视图注入到在xml中声明的viewGroup?

在运行时更改Django中的自定义设置变量

如何在运行时生成实例方法并将其添加到类中,但仅将方法编译一次?

FluentValidation-如何在运行时自定义验证消息

是否可以在运行时在Spring Boot中构建自定义查询?

在运行时使用属性窗口自定义窗体控件

如何在运行时重新加载自定义属性?ASP.NET 核心 MVC

有没有可能将事件(自定义)附加到在运行时创建的对象上?[C++ Builder]

如何在运行时使用其他形状制作自定义圆形?

在运行时错误 Delphi 中创建自定义 TPanel

如何通过自定义属性注册瞬态服务并在运行时按名称检索它们?