2010-06-21 73 views
1

我在下面的代码问题:德尔福2010 RTTI和指针字段

program Project4; 

{$APPTYPE CONSOLE} 

uses 
    SysUtils, RTTI; 

type 

    TRecord2 = record 
    c: integer; 
    d: integer; 
    end; 

    TClass1 = class 
    public 
    FRecord: record 
     a: integer; 
     b: integer; 
    end; 
    FRecord2: TRecord2; 
    FPointRecord3: ^TRecord2; 

    constructor Create; 
    end; 

constructor TClass1.Create; 
begin 
    FPointRecord3 := nil; 
end; 

var 
    lContext: TRttiContext; 
    lType: TRttiType; 
    lFields: TArray<TRttiField>; 
    i: integer; 
begin 
    try 
    { TODO -oUser -cConsole Main : Insert code here } 
    lContext := TRttiContext.Create; 

    lType := lContext.GetType(TClass1); 

    lFields := lType.GetFields; 
    for i := 0 to Length(lFields) - 1 do 
    begin 
     write('Name = '+lFields[i].Name+', '); 
     if lFields[i].FieldType <> nil then 
     writeln('Type = '+lFields[i].FieldType.ToString) 
     else 
     writeln('Type = NIL!!!'); 
    end; 
    lContext.Free; 
    except 
    on E: Exception do 
     Writeln(E.ClassName, ': ', E.Message); 
    end; 
end. 

输出:

Name = FRecord, Type = :TClass1.:1 
Name = FRecord2, Type = TRecord2 
Name = FPointRecord3, Type = NIL!!! 

lFields [I] .FieldType返回NIL 如何获得与RTTI类型的指针类型的字段?

回答

3

它不会创建任何类型信息,因为您从未实际为其定义类型。您只是将字段定义为指向定义类型的指针,因此编译器会即时为其创建临时“类型”,但不会生成RTTI。

如果你想它的工作,像这样做:

type 

    TRecord2 = record 
    c: integer; 
    d: integer; 
    end; 
    PRecord2 = ^TRecord2; 

    TClass1 = class 
    public 
    FRecord: record 
     a: integer; 
     b: integer; 
    end; 
    FRecord2: TRecord2; 
    FPointRecord3: PRecord2; 

    constructor Create; 
    end; 
+1

我有同样的代码,你只落后2秒:-) – 2010-06-21 16:13:51

+0

谢谢。有用。 – Mielofon 2010-06-22 04:20:31