作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在 Delphi-Tokyo 中学习 RTTI 以创建 ORM,但我在访问也是对象的属性时遇到问题。在下面的代码中,如何对 id
执行 Prop
的转换?
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, rtti, Vcl.StdCtrls;
type
TIntField = class(TObject)
private
fDisplayNme: string;
public
constructor Create(DisplayName: string);
published
property DisplayName: string read fDisplayNme write fDisplayNme;
end;
TSale = class(TObject)
private
fIdSale: TIntField;
public
constructor Create;
published
property IdSale: TIntField read fIdSale write fIdSale;
end;
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
{ TIntField }
constructor TIntField.Create(DisplayName: string);
begin
fDisplayNme:= DisplayName;
end;
{ TSale }
constructor TSale.Create;
begin
fIdSale:= TIntField.Create('idSale');
end;
procedure TForm1.Button1Click(Sender: TObject);
var
Context: TRttiContext;
TypObj: TRttiType;
Prop: TRttiProperty;
sale: TSale;
id: TIntField;
begin
sale:= TSale.Create;
Context:= TRttiContext.Create;
TypObj:= Context.GetType(sale.ClassInfo);
prop:= TypObj.GetProperty('IdSale');
id:= Prop as TIntField; //Would you like to do this or something equivalent
ShowMessage(id.DisplayName);
end;
end.
最佳答案
调用GetValue
关于TRttiProperty
实例,传递实例指针。这会产生 TValue
您可以使用 AsType<T>
从中提取对象。像这样:
var
Context: TRttiContext;
Typ: TRttiType;
Prop: TRttiProperty;
sale: TSale;
id: TIntField;
....
sale := TSale.Create;
Typ := Context.GetType(sale.ClassInfo);
Prop := Typ.GetProperty('IdSale');
id := Prop.GetValue(sale).AsType<TIntField>;
Writeln(id.DisplayName);
关于delphi - 如何对对象执行 TRTTIProperty 的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44885924/
我想知道是否可以直接引用类定义,以便将其与 RTTI 结合使用(将属性映射到 TRttiProperty 等)。 例如 我想使用 TMyClass.MyProperty 作为 TRttiPropert
我正在 Delphi-Tokyo 中学习 RTTI 以创建 ORM,但我在访问也是对象的属性时遇到问题。在下面的代码中,如何对 id 执行 Prop 的转换? unit Unit1; interfac
我想在 Delphi 中序列化一个对象,并且我正在使用新的 RTTI。但是当我从存储中加载值时,它们会作为字符串检索,并且 TRttiProperty.SetValue 需要 TValue 作为第二个
我正在尝试使用TRttiProperty.SetValue过程通过rtti分配一个对象过程类型的属性,但是当我尝试制作时会引发此异常赋值EInvalidCast:无效的类类型转换 此示例应用程序显示了
我是一名优秀的程序员,十分优秀!