【发布时间】:2017-10-19 14:05:32
【问题描述】:
我有几个具有简单类型(整数、布尔值、字符串)和一些 Nullable 属性的类:
Nullable<T> = record
private
FValue: T;
FHasValue: IInterface;
function GetValue: T;
function GetHasValue: Boolean;
public
constructor Create(AValue: T);
property HasValue: Boolean read GetHasValue;
property Value: T read GetValue;
end;
例如。
TMyClass1 = class(TCommonAncestor)
private
FNumericvalue: Double;
FEventTime: Nullable<TDateTime>;
public
property NumericValue: Double read FNumericValue write FNumericValue;
property EventTime: Nullable<TDateTime> read FEventTime write FEventTime;
end;
和
TMyClass2 = class(TCommonAncestor)
private
FCount: Nullable<Integer>;
FName: string;
public
property Count: Nullable<Integer> read FCount write FCount;
property Name: string read FName write FName;
end;
等等……
鉴于 TCommonAncestor 的后代,我想使用 RTTI 迭代所有公共属性并列出它们的名称和值,除非它是一个 Nullable,其中 T.HasValue 返回 false。
我正在使用 Delphi XE2。
编辑:添加了我目前的内容。
procedure ExtractValues(Item: TCommonAncestor);
var
c : TRttiContext;
t : TRttiType;
p : TRttiProperty;
begin
c := TRttiContext.Create;
try
t := c.GetType(Item.ClassType);
for p in t.GetProperties do
begin
case p.PropertyType.TypeKind of
tkInteger:
OutputDebugString(PChar(Format('%se=%s', [p.Name,p.GetValue(Item).ToString]));
tkRecord:
begin
// for Nullable<Double> p.PropertyType.Name contains 'Nullable<System.Double>'
// but how do I go about accessing properties of this record-type field?
end;
end;
end;
finally
c.Free;
end;
end;
【问题讨论】:
-
到目前为止,您尝试了哪些方法来解决这个问题?公共属性无法通过传统 RTTI(
System.TypInfo单元)访问,因此您必须使用扩展 RTTI(System.Rtti单元) -
我已经修改了我的问题以表明我正在尝试使用 System.Rtti
-
无法使用 RTTI 访问记录属性。您将不得不改为使用记录字段。
-
@LU RD 你能详细说明一下吗?
-
@LURD: How to access record properties? 询问如何访问记录类型内部的属性,由于缺少记录属性的 RTTI,这确实不起作用。但这不是这个问题的目的。这个问题是询问如何访问记录类型的属性,并且与 RTTI 配合得很好。
标签: delphi generics delphi-xe2