如何通过RTTI区分TDateTime属性和Double属性?

Bar*_*rry 18 delphi rtti tdatetime

使用Delphi 2010中的RTTI系统,有没有办法找出属性是否是TDateTime?每当我回调asVariant并且如果我检查属性类型时,它当前将它视为双精度.这是因为它只能看到基本类型吗?(TDateTime = double)

RRU*_*RUZ 24

尝试检查的Name属性TRttiProperty.PropertyType

我没有Delphi 2010,但这适用于XE.

{$APPTYPE CONSOLE}

uses
  SysUtils,
  Classes,
  Rtti;

type
  TMyClass =class
  private
    FDate: TDateTime;
    FProp: Integer;
    FDate2: TDateTime;
    FDate1: TDateTime;
  public
   property Date1 : TDateTime read FDate1  Write FDate1;
   property Prop : Integer read FProp  Write FProp;
   property Date2 : TDateTime read FDate2  Write FDate2;
  end;

var
 ctx : TRttiContext;
 t :  TRttiType;
 p :  TRttiProperty;
begin
 ctx := TRttiContext.Create;
 try
   t := ctx.GetType(TMyClass.ClassInfo);
   for p in  t.GetProperties do
    if CompareText('TDateTime',p.PropertyType.Name)=0 then
     Writeln(Format('the property %s is %s',[p.Name,p.PropertyType.Name]));
 finally
   ctx.Free;
 end;
  Readln;
end.
Run Code Online (Sandbox Code Playgroud)

此代码返回

the property Date1 is TDateTime
the property Date2 is TDateTime
Run Code Online (Sandbox Code Playgroud)

  • 这也适用于至少Delphi 5与旧的TypInfo方法. (3认同)