现在的位置: 首页 > 综合 > 正文

Rtti 单元(3): 获取有序类型的信息

2013年09月04日 ⁄ 综合 ⁄ 共 1444字 ⁄ 字号 评论关闭

任何数据类型中 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.

抱歉!评论已关闭.