How can I distinguish TDateTime properties from Double properties with RTTI?

感情迁移 提交于 2019-12-05 13:21:50

问题


Using the RTTI system in Delphi 2010, is there any way to find out if a property is a TDateTime? It's currently treating it as a double whenever I call back asVariant and also if I check the property type. Is this due to the fact it can only see the base type? (TDateTime = double)


回答1:


Try checking the Name property of the TRttiProperty.PropertyType

I don't have Delphi 2010, but this works in 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.

this code returns

the property Date1 is TDateTime
the property Date2 is TDateTime



回答2:


Key point here while defining type is the type directive. These two definitions are different:

Type
  TDateTime = Double; // here p.PropertyType.Name returns Double

but

Type
  TDateTime = type Double; // here p.PropertyType.Name returns TDateTime

or 

Type
  u8 = type Byte; // here p.PropertyType.Name returns u8

but

Type
  u8 = Byte; // here p.PropertyType.Name returns Byte !


来源:https://stackoverflow.com/questions/7836880/how-can-i-distinguish-tdatetime-properties-from-double-properties-with-rtti

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!