加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-15 09:51:21 所属栏目:大数据 来源:网络整理
导读:是否可以以及如何在运行时创建自定义属性并将其附加到字段? uses System.SysUtils,System.Classes,System.Rtti;type MyAttribute = class(TCustomAttribute) private fCaption: string; public constructor Create(const aCaption: string); property Capti
是否可以以及如何在运行时创建自定义属性并将其附加到字段?

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

我想将值为空的MyAttribute注入到在运行时没有它的字段,从而产生以下输出:

Bar Title
Other Empty

解决方法

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读