任何数据类型中 Rtti 中都有对应的获取信息的类, 有序类型对应的是 TRttiOrdinalType.

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Memo1: TMemo;
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

uses Rtti;

procedure TForm1.Button1Click(Sender: TObject);
var
  t: TRttiOrdinalType;
begin
  Memo1.Clear;

  //先从类型名获取类型信息对象
  t := TRttiContext.Create.GetType(TypeInfo(Byte)) as TRttiOrdinalType;
  Memo1.Lines.Add(Format('%s - %s', [t.Name, t.QualifiedName]));
  Memo1.Lines.Add(Format('Size: %d', [t.TypeSize]));
  Memo1.Lines.Add('QualifiedName: ' + t.QualifiedName);
  Memo1.Lines.Add(Format('Min,Max: %d , %d', [t.MinValue, t.MaxValue]));
  Memo1.Lines.Add(EmptyStr); //空字串

  //可以用 AsOrdinal 方法代替前面的 as TRttiOrdinalType
  t := TRttiContext.Create.GetType(TypeInfo(Word)).AsOrdinal;
  Memo1.Lines.Add(Format('%s: %s', [t.Name, t.QualifiedName]));
  Memo1.Lines.Add(Format('Size: %d', [t.TypeSize]));
  Memo1.Lines.Add(Format('Min,Max: %d , %d', [t.MinValue, t.MaxValue]));
  Memo1.Lines.Add(EmptyStr);

  //也可以直接强制转换
  t := TRttiOrdinalType(TRttiContext.Create.GetType(TypeInfo(Integer)));
  Memo1.Lines.Add(Format('%s: %s', [t.Name, t.QualifiedName]));
  Memo1.Lines.Add(Format('Size: %d', [t.TypeSize]));
  Memo1.Lines.Add(Format('Min,Max: %d , %d', [t.MinValue, t.MaxValue]));
  Memo1.Lines.Add(EmptyStr);
end;

end.

posted on 2009-10-15 21:25  万一  阅读(3728)  评论(5编辑  收藏  举报